08 February 2011

.NET - Generic casting to nullable types

The following is part of a function that reads a value from an XML node and casts it to a given type. The function uses:

Convert.ChangeType(value, type)

to do the casting, but this doesn't work for nullable types.
To solve this problem, the following section was added:

else if (type.IsGenericType &&
         type.GetGenericTypeDefinition().Equals(typeof(Nullable<>))) {
  if (string.IsNullOrEmpty(value)) {
    return defaultValue; //Commonly 'null'
  }
  else {
    NullableConverter nullConv = new NullableConverter(type);
    return Convert.ChangeType(value, nullConv.UnderlyingType);
  }
}

The result of this function, which returns an object, is casted to the desired - nullable - type on the line where it is called.

No comments:

Post a Comment