4

If I do this:

Type type = typeof(Nullable<int>);

The type variable holds the correct Nullable'1 type.

However, If I try to do this:

Nullable<int> n = 2;
Type type = n.GetType();

type ends up holding System.Int32 which is the underlying type, but not what I am expecting.

How can I get the type of a Nullable<> instance?

Keep in mind that I don't know the underlying type of the nullable instance, so I cannot call typeof.

Matias Cicero
  • 25,439
  • 13
  • 82
  • 154
  • @NirajDoshi I don't see how this is a duplicate. I'm not asking why am I not getting the correct type, but rather how can I get the correct one. – Matias Cicero Nov 04 '15 at 18:09
  • 1
    Check the other duplicate, it contains an explanation *and* a solution which is similar to the answer posted below. – Panagiotis Kanavos Nov 04 '15 at 18:11
  • http://stackoverflow.com/a/6931816/1228 is the answer in the dupe that tells you. –  Nov 04 '15 at 18:14

1 Answers1

3

Not elegant, but you can wrap it in a generic function:

public static void Main()
{
    int? i = 2;
    Console.WriteLine( type(i) );
}

public static Type type<T>( T x ) { return typeof(T); }
clcto
  • 9,530
  • 20
  • 42