I have the below code and I’d need to convert a string to a type which is also specified from String:
Type t = Type.GetType("System.Nullable`1[[System.DateTime, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]");
object d = Convert.ChangeType("2012-02-23 10:00:00", t);
I get the below error messagE:
Invalid cast from 'System.String' to 'System.Nullable`1[[System.DateTime, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]'.
How would that be nicely possible?
I know one ugly way would be to check whether the type is nullable using if:
Type possiblyNullableType = Type.GetType("System.Nullable`1[[System.DateTime, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]");
var underlyingType = Nullable.GetUnderlyingType(possiblyNullableType);
Object result;
// if it's null, it means it wasn't nullable
if (underlyingType != null)
{
result = Convert.ChangeType("2012-02-23 10:00:00", underlyingType);
}
Would there be any better way?
Thanks,
There are two problems.
Firstly,
Convert.ChangeTypejust plain does not support nullable types.Secondly, even if it did, by boxing the result (assigning it to an
object), you’d already be converting it to aDateTime.You could special case nullable types: