1

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

Ilia G
  • 10,043
  • 2
  • 40
  • 59

2 Answers2

7

o can never refer to an instance of Nullable<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 return Nullable<T> for any value of o - regardless of the type of o. For example:

Nullable<int> x = 10;
Console.WriteLine(x.GetType()); // System.Int32

Here we end up boxing the value of x because GetType() is declared on object and not overridden in Nullable<T> (because it's non-virtual). It's a little bit of an oddity.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
0

It does not makes sense.

If you have code:

int? x = null; //int? == Nullable<int>
if ( null == x ) { Console.WriteLine("x is null"); }
else { Console.WriteLine( "x is " + x.ToString() ); }

The result will be "x is null" printed in console.

TcKs
  • 25,849
  • 11
  • 66
  • 104