If have this in the setter of a property:
decimal? temp = value as decimal?;
value = \"90\"
But after the cast, temp is nul
If you do not want to parse strings, but want to ensure that you receive either null
, a decimal
or a nullable decimal
, then you could do something like this:
public static Nullable Convert(object input)
where T : struct
{
if (input == null)
return null;
if (input is Nullable || input is T)
return (Nullable)input;
throw new InvalidCastException();
}
You could make it return null on the last line instead if you wished to avoid exceptions, although this would not distinguish between real null values and bad casts.
Note that you have to use the "is" operator, as the "as" operator does not work on value types, and casting without checking may thrown an InvalidCastException.
You could also make it an extension method:
public static class ObjectExtensions
{
public static Nullable ToNullable(this object input)
where T : struct
{
if (input == null)
return null;
if (input is Nullable || input is T)
return (Nullable)input;
throw new InvalidCastException();
}
}
And use it like this:
object value = 123.45m;
decimal? dec = value.ToNullable();
This will help avoid code contract warnings about unboxing null references.