7

I don't really know what to add to the title, I'd like to get the Type (T) of a Nullable. For example, I got a an object whose Type is Nullable and I'd like to get something like "System.Int32" (the type of course, not the string)

Guillaume Slashy
  • 3,554
  • 8
  • 43
  • 68
  • I believe this is a dupe but can't find it, but you're looking for [Nullable.GetUnderlyingType](http://msdn.microsoft.com/en-us/library/system.nullable.getunderlyingtype.aspx). Could be http://stackoverflow.com/questions/5174423/getting-basic-datatype-rather-than-weird-nullable-one-via-reflection-in-c-sha or http://stackoverflow.com/questions/5181494/determine-if-a-generic-param-is-a-nullable-type – user7116 Nov 29 '11 at 15:23
  • http://blog.dotnetclr.com/archive/2008/03/11/get-underlying-type-from-a-nullable-type.aspx – Oded Nov 29 '11 at 15:23
  • 3
    The question is ambiguous. Do you have a Type object representing a nullable value type, and you want to know the underlying value type? Or do you have an *instance* of an object of nullable value type and you want to know the underlying value type? The answers to those two questions are completely different. In the first case, you can use GetUnderlyingType. In the second case, either the object instance is boxed or it is not. If it is boxed then *it is not of nullable type*. There is no such thing as a boxed nullable value type. If it is not boxed then *you already know its type*. – Eric Lippert Nov 29 '11 at 15:40
  • I had a type representing the object. For an instance, I would have to use Activator.CreateInstance which could be possible but kinda useless imo, since I can get what i want from the Type ! – Guillaume Slashy Nov 30 '11 at 09:48

6 Answers6

12

Try this : Nullable.GetUnderylingType(myType)

FYI : myType must be a Type

Steven Muhr
  • 3,339
  • 28
  • 46
2

This method should do the trick:

Type GetValueType(Type t)
{
   return t.GetGenericArguments().First();
}
Bas
  • 26,772
  • 8
  • 53
  • 86
1

Use GetType() it works as (un)expected.

if (typeof(int?) == typeof(int))
    MessageBox.Show("It works with definitions");
if (new Nullable<int>(2).GetType() == typeof(int))
    MessageBox.Show("It works with instances!");

This sample code will show the last message box. GetType() will return the underlying type.

Casperah
  • 4,504
  • 1
  • 19
  • 13
0

A Nullable is a Generic construction, so you should get it from the GenericArguments from the type, like this: typeof(T).GetGenericArguments()[0]

Kolky
  • 2,917
  • 1
  • 21
  • 42
0
System.Nullable.GetUnderlyingType(typeof(Nullable<int>));
Dylan Meador
  • 2,381
  • 1
  • 19
  • 32
0

Warning: horrible code, no checks, just an example etc:

using System;

static class Program {

    public static void Main(params string[] args) {
        Type t = typeof(int?);
        Type genericArgument = t.GetGenericArguments()[0];
        Console.WriteLine(genericArgument.FullName);
    }
}
Paolo Tedesco
  • 55,237
  • 33
  • 144
  • 193