0

I want to understand usage of Nullable.GetUnderlyingType(). When should it be used?

Also, in the following example, How can we make use of GetUnderlyingType instead of GetType

    int? x = 1;
    Console.WriteLine(x.GetType().Name);

I tried to follow Whats the use of Nullable.GetUnderlyingType, if typeof(int?) is an Int32? link, but kept my head scratching.

Community
  • 1
  • 1
Tilak
  • 30,108
  • 19
  • 83
  • 131
  • You don't need it, since you know the type of x statically... – Thomas Levesque Feb 16 '12 at 17:20
  • My question is for the case where we dont know the type at compile time. x.GetType can throw exception if x is null. – Tilak Feb 16 '12 at 17:26
  • 1
    When should it be used? When you need to know the underlying type of a nullable! It's also handy to test whether or not *any* arbitrary type is a nullable: `if (Nullable.GetUnderlyingType(typeToTest) != null) { /* typeToTest is nullable */ }` – LukeH Feb 16 '12 at 17:29
  • Well after little thought, I understood, it is not possible to have type not known statically, and getting null value. So my comment is invalid. – Tilak Feb 16 '12 at 17:30

1 Answers1

0

Assuming that you have obtained a property of a class via reflection (call it vProp), the following should work:

Type tNullType = Nullable.GetUnderlyingType(vProp.PropertyType);
Type tType = tNullType ?? vProp.PropertyType;

tType will return the actual property type, whether Nullable or not, that you can use for casting or other similar operations.

Roman
  • 631
  • 1
  • 13
  • 14