Wanted a simple but efficient method to get value from Nullable when T is not known at the compile time.
So far have something like this:
public static object UnwrapNullable(object o)
{
if (o == null)
return null;
if (o.GetType().IsGenericType && o.GetType().GetGenericTypeDefinition() == typeof(Nullable<>))
return ???
return o;
}
anything can be done here without dipping into dynamic code generation?
used on .NET 2.0
ocan never refer to an instance ofNullable<T>. If you box a nullable value type value, you either end up with a boxed value of the non-nullable underlying type, or a null reference.In other words,
o.GetType()can never returnNullable<T>for any value ofo– regardless of the type ofo. For example:Here we end up boxing the value of
xbecauseGetType()is declared onobjectand not overridden inNullable<T>(because it’s non-virtual). It’s a little bit of an oddity.