why is typeof int?
an Int32
int? x = 1;
Console.WriteLine(x.GetType().Name);
If it is okay then what\'s the use of
This example is a bit confused, because:
int? x = 1;
creates a Nullable
like you expect; however:
Type tupe = x.GetType();
is a call to a non-virtual method on object
, which isn't (and can't be) overridden - therefore this is a boxing operation; and Nullable
has special boxing rules:
null
i.e.
int? x = 1;
int y = 1;
box to exactly the same thing.
Therefore, you are passing typeof(int)
to GetUnderlyingType
.
A more illustrative example of when this helps is when using reflection:
class Foo {
public int? Bar {get;set;}
}
...
Type type = typeof(Foo); // usually indirectly
foreach(var prop in type.GetProperties()) {
Type propType = prop.PropertyType,
nullType = Nullable.GetUnderlyingType(propType);
if(nullType != null) {
// special code for handling Nullable properties;
// note nullType now holds the T
} else {
// code for handling other properties
}
}