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.