Home > OS >  Correct way to get nullable type from Type.GetType(string)
Correct way to get nullable type from Type.GetType(string)

Time:02-16

How do I get the type of a nullable using Type.GetType(string) from a string like: System.Boolean? and System.Nullable<System.Boolean>?

Both of these are wrong and I'm not sure what's the correct way.

By wrong I mean writing Type.GetType(X) returns null

CodePudding user response:

As documented in the remarks of Type.GetType(string):

The name of a generic type ends with a backtick (`) followed by digits representing the number of generic type arguments. The purpose of this name mangling is to allow compilers to support generic types with the same name but with different numbers of type parameters, occurring in the same scope.

For generic types, the type argument list is enclosed in brackets, and the type arguments are separated by commas.

Therefore, to get the System.Type of bool? from a string, you need to use the following:

Type.GetType("System.Nullable`1[System.Boolean]");

Where:

System.Nullable is the generic type name.

`1 identifies the number of generic arguments (1).

[System.Boolean] specifies the generic argument.

  • Related