1

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?

Aren
  • 54,668
  • 9
  • 68
  • 101
  • I can't quite tell what you're asking, but you should know that an `object` will never be `int?` or `decimal?`. It will just be `null` if your `Nullable<>` doesn't have a value. – Gabe May 08 '10 at 20:32

2 Answers2

6

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
  • 134,786
  • 31
  • 255
  • 325
  • 1
    How about "`return Nullable.GetUnderlyingType(theType) != null;`" instead? http://msdn.microsoft.com/en-us/library/system.nullable.getunderlyingtype.aspx – LukeH May 08 '10 at 22:22
0

From MSDN:

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

Oded
  • 489,969
  • 99
  • 883
  • 1,009