Search code examples
c#typesnullable

Get a nullable type from a type name


I have the following scenario where I get a string that looks as follows

"System.DateTime?"

or

"int?"

What I would like to be able to do, is retrieve the System.Type for that string which would look like:

{Name = "Nullable1" FullName = "System.Nullable1[[System.DateTime, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]"}

Now I know how to retrieve the type from a string I can just say Type.GetType("System.DateTime") when dealing with non nullable type or typeof(DateTime?) when I know it's going to be DateTime nullable, but in this instance I'm unaware of the what nullable type might come through and will only receive it as string.


Solution

  • I'm missing part of the context - for example, does the string always represent a nullable value type?

    Given that you can extract the value type name from the string and create a reference to that type:

    var valueType = Type.GetType("System.DateTime");
    var nullableType = typeof(Nullable<>).MakeGenericType(valueType);
    

    That should solve part of the problem. The harder part will be determining the underlying type from the string, which depends on what sort of inputs you're receiving. It's easy to get a type from System.DateTime, but harder from int. This answer may help with that part.


    As far as the input - is there any option that you could provide a list of available choices to the user so that input you receive would always be a valid type name? That would negate the need for any of this. Then you could just do Type.GetType(stringWithTypeName).