How to write a general conversion method that will support conversion to and from NULL types?

Possible duplicate:
How can I fix this to make a general conversion to Nullable <T>?

public static class ObjectExtensions
    {
        public static T To<T>(this object value)
        {
            return (T)Convert.ChangeType(value, typeof(T));
        } 
    }

My above extension method helps convert a type to another type, but does not support types with a null value.

For example, {0} works fine, but {1} does not work:

{0}:
var var1 = "12";
var var1Int = var1.To<int>();

{1}:
var var2 = "12";
var var2IntNullable = var2.To<int?>();

So, how to write a general conversion method that will support converting to and from NULL types?

Thank,

+5
source share
1 answer

This works for me:

public static T To<T>(this object value)
{
    Type t = typeof(T);

    // Get the type that was made nullable.
    Type valueType = Nullable.GetUnderlyingType(typeof(T));

    if (valueType != null)
    {
        // Nullable type.

        if (value == null)
        {
            // you may want to do something different here.
            return default(T);
        }
        else
        {
            // Convert to the value type.
            object result = Convert.ChangeType(value, valueType);

            // Cast the value type to the nullable type.
            return (T)result;
        }
    }
    else 
    {
        // Not nullable.
        return (T)Convert.ChangeType(value, typeof(T));
    }
} 
+11
source

All Articles