I want to cast a string to a decimal?. With reference to a previous question here
one of the answers gave a object extension to convert objects like so
public static class ObjectExtensions
{
public static Nullable<T> ToNullable<T>(this object input)
where T : struct
{
if (input == null)
return null;
if (input is Nullable<T> || input is T)
return (Nullable<T>)input;
throw new InvalidCastException();
}
}
usage :
object value = 123.45m;
decimal? dec = value.ToNullable<decimal>();
The above does not work with string however, is it possible to define a companion to the above method to specifically handle strings?
specifically like what I would like to be able to do is :-
object v1 = 123.45m;
decimal? d1 = v1.ToNullable<decimal>();
object v2 = "123.45";
decimal? d2 = v2.ToNullable<decimal>();