views:

66

answers:

2

Ok, im still a bit new to using nullable types.

I'm writing a reflecting object walker for a project of mine, im getting to the point where im setting the value of a reflected property with the value i've retrieved from a reflected property.

The value i've retrieved is still in object form, and it dawned on me, since i want my object walker to return null when it can't find something, (I thought about throwing an exception, but i want this to soft-fail when something's wrong).

Anyway, some of the values im setting/getting are decimal bool etc... so it dawned on me that i should just NOT set a non-nullable value, but I realized I straight up don't know how to tell decimal from decimal?

Is it enough to key on if the Type of the property im setting is inherited from ValueType?

+6  A: 

The following code will tell you whether a type is nullable or not:

private bool IsNullableType(Type theType)
{
    return theType.IsGenericType && 
           theType.GetGenericTypeDefinition().Equals(typeof(Nullable<>));
}
ChrisF
How about "`return Nullable.GetUnderlyingType(theType) != null;`" instead? http://msdn.microsoft.com/en-us/library/system.nullable.getunderlyingtype.aspx
LukeH
@Luke - That would work too.
ChrisF
A: 

From MSDN:

Nullable types are instances of the System.Nullable<T> struct.

Oded