Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write a generic conversion method which would support converting to and from nullable types? [duplicate]

Possible Duplicate:
How can I fix this up to do generic 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 converting a type to another type but it doesn't support nullable types.

For example, {0} works fine but {1} doesn't work:

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

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

So, how to write a generic conversion method which would support converting to and from nullable types?

Thanks,

like image 450
The Light Avatar asked Mar 19 '12 15:03

The Light


People also ask

Can a generic type be null?

This means that you can put any object in a collection because all classes in the C# programming language extend from the object base class. Also, we cannot simply return null from a generic method like in normal method.

Which operator is used to converts the input to the specified .NET Framework type?

The Explicit operator, which defines the available narrowing conversions between types. For more information, see the Explicit Conversion with the Explicit Operator section. The IConvertible interface, which defines conversions to each of the base . NET data types.

How does convert ChangeType work?

ChangeType(Object, TypeCode) is a general-purpose conversion method that converts the object specified by value to a predefined type specified by typeCode . The value parameter can be an object of any type.


1 Answers

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));
    }
} 
like image 106
RobSiklos Avatar answered Oct 02 '22 05:10

RobSiklos