Search code examples
c#asp.netgenericsdatetimenullable

How to Convert a String to a Nullable Type Which is Determined at Runtime?


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,


Solution

  • There are two problems.

    Firstly, Convert.ChangeType just 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 a DateTime.

    You could special case nullable types:

    string s = "2012-02-23 10:00:00";
    Type t = Type.GetType("System.Nullable`1[[System.DateTime, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]");
    object d;
    
    if (t.IsGenericType && t.GetGenericTypeDefinition() == typeof(Nullable<>))
    {
        if (String.IsNullOrEmpty(s))
            d = null;
        else
            d = Convert.ChangeType(s, t.GetGenericArguments()[0]);
    }
    else
    {
        d = Convert.ChangeType(s, t);
    }