Type conversion (From object to Nullable, Enum, Custom TypeConverter)

While building our Commerce Server 2007 solution it made sense to wrap the LineItem class to easily access the weakly typed indexer accessible properties (which are exposed as object).

Because the underlying datatype could have been anything (ref/value type, nullable, custom) I created a helper method that accepts an object value and returns the value casted to the appropriate type. The can obviously be used in many contexts so I thought I’d share.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
public static T ConvertTo(object value)
{
// check for value = null, thx alex
Type t = typeof(T);
// do we have a nullable type?
if (t.IsGenericType && t.GetGenericTypeDefinition().Equals(typeof(Nullable<>)))
{
NullableConverter nc = new NullableConverter(t);
t = nc.UnderlyingType;
}
if (t.IsEnum) // if enum use parse
return (T)Enum.Parse(t, value.ToString(), false);
else
{
// if we have a custom type converter then use it
TypeConverter td = TypeDescriptor.GetConverter(t);
if (td.CanConvertFrom(value.GetType()))
{
return (T)td.ConvertFrom(value);
}
else // otherwise use the changetype
return (T)Convert.ChangeType(value, t);
}
}
DateTime dt = TypeConversionUtility.ConvertTo(dateVal);

Use of included code sample is subject to the terms specified at http://www.microsoft.com/info/cpyright.htm

This posting is provided “AS IS” with no warranties, and confers no rights.

Share