19 June 2006

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.

public static T ConvertTo<T>(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<DateTime>(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.

 

Comment Notification

If you would like to receive an email when updates are made to this post, please register here

Subscribe to this post's comments using RSS

Comments

# Alex said:
That method needs some validation when 'value' parameter is null.

int? num = ConvertTo<int?>(null);
20 June 06 at 8:25 PM
# jongallant said:
Very true.  I was checking this higher in the stack and left it out, but good coding practices would have checked for null in this method.

Thanks!
20 June 06 at 8:33 PM
# Jakub said:

Hi. I've found this post very usefull and was able to use it in my application.

One thing you may consider is this: When you create TypeDescriptor for the target type, it is not usable in all cases, i.e. converting string to Guid fails. This was my solution:

// if we have a custom type converter then use it

TypeConverter td = TypeDescriptor.GetConverter(type);

if (td.CanConvertFrom(valueType))

{

   return td.ConvertFrom(value);

}

//if ConvertFrom is not usable, try the other way around:

td = TypeDescriptor.GetConverter(valueType);

if (td.CanConvertTo(type))

{

   return td.ConvertTo(value, type);

} // if

else // otherwise use the changetype

{...}

21 December 06 at 9:16 AM
# hardcorevibes.de » Basistyp von einen generischen Nullable Typ ermitteln said:

PingBack from http://www.hardcorevibes.de/?p=87

15 March 07 at 5:08 AM
# Jay R. Wren - lazy dawg evarlast » Blog Archive » Blog Code Snippets License Examples said:

PingBack from http://jrwren.wrenfam.com/blog/2007/10/12/blog-code-snippets-license-examples/

12 October 07 at 2:35 PM
# Womens Discount Perfume » Not child perfume but still interesting… said:

PingBack from http://discount-perfume-hq.com/?p=1906

30 October 07 at 6:25 PM
# Womens Discount Perfume » Not perfume online but still interesting… said:

PingBack from http://discount-perfume-hq.com/?p=2806

31 October 07 at 10:46 AM

Leave a Comment

Comment Policy: No HTML allowed. URIs and line breaks are converted automatically. Your e–mail address will not show up on any public page.

(required) 
(optional)
(required) 

  
Enter Code Here: Required
Page view tracker