Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading