Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert value from object to Nullable<> [duplicate]

Tags:

c#

I have some class with some properties and I want to convert values from string to type of this properties. And I have problem with conversion to nullable types. This is my method for converting:

public static object ChangeType(object value, Type type)
{
    if (type.IsGenericType && type.GetGenericTypeDefinition().Equals(typeof(Nullable<>)))
    {
        if (value == null)
        {
            return null;
        }

        var underlyingType = Nullable.GetUnderlyingType(type);
        var val = Convert.ChangeType(value, underlyingType);
        var nullableVal = Convert.ChangeType(val, type); // <-- Exception here
        return nullableVal;
    }

    return Convert.ChangeType(value, type);
}

I'm getting exception like this (for property of type int?):

Invalid cast from 'System.Int32' to 'System.Nullable`1[[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]'.

How can I convert from type to nullable type? Thanks.

like image 804
Vitone Avatar asked May 27 '15 13:05

Vitone


2 Answers

It is impossible... Boxing of value types "erases" the Nullable<> part...

int? num = 5;
object obj = num;
Console.WriteLine(obj.GetType()); // System.Int32

and

int? num = null;
object obj = num;
Console.WriteLine(obj == null); // True

Note that this characteristic is what makes Nullable<> "special". They need direct support from the CLR. Nullable<> isn't simply a struct that you could write.

What you can do:

public static object ChangeType(object value, Type type)
{
    // returns null for non-nullable types
    Type type2 = Nullable.GetUnderlyingType(type);

    if (type2 != null)
    {
        if (value == null)
        {
            return null;
        }

        type = type2;
    }

    return Convert.ChangeType(value, type);
}
like image 141
xanatos Avatar answered Oct 11 '22 18:10

xanatos


var nullableVal = Activator.CreateInstance(type, val);

Using the activator will allow you to create a new instance of the int? class with an argument being passed to the constructor of the int value. The below code is a literal demonstration of such:

var type = typeof(int?);

var underlyingType = typeof(int);

var val = 123;

var nullableVal = Activator.CreateInstance(type, val);
like image 34
Will Custode Avatar answered Oct 11 '22 18:10

Will Custode