How to get instance type Nullable <T>

If I do this:

Type type = typeof(Nullable<int>);

The variable typecontains the correct type Nullable'1.

However, if I try to do this:

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

typeends with a hold System.Int32, which is the base type, but not what I expect.

How can I get the instance type Nullable<>?

Keep in mind that I do not know the base instance type with the NULL capability, so I cannot call typeof.

+4
source share
1 answer

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); }
+3
source

Source: https://habr.com/ru/post/1614496/


All Articles