Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I convert a System.Type to its nullable version?

Tags:

c#

.net

Once again one of those: "Is there an easier built-in way of doing things instead of my helper method?"

So it's easy to get the underlying type from a nullable type, but how do I get the nullable version of a .NET type?

So I have

typeof(int) typeof(DateTime) System.Type t = something; 

and I want

int?  DateTime? 

or

Nullable<int> (which is the same) if (t is primitive) then Nullable<T> else just T 

Is there a built-in method?

like image 203
Alex Duggleby Avatar asked Sep 20 '08 13:09

Alex Duggleby


People also ask

How do you declare as nullable?

You can declare nullable types using Nullable<t> where T is a type. Nullable<int> i = null; A nullable type can represent the correct range of values for its underlying value type, plus an additional null value. For example, Nullable<int> can be assigned any value from -2147483648 to 2147483647, or a null value.

How do you make a method nullable in C#?

anint = null) . This way you can call to the method only with a string as parameter and the value of the anint variable will be null; and also call it with the string and the integer.

What is System nullable in C#?

In C#, the compiler does not allow you to assign a null value to a variable. So, C# 2.0 provides a special feature to assign a null value to a variable that is known as the Nullable type. The Nullable type allows you to assign a null value to a variable.

What do you mean by nullable type?

Nullable types are a feature of some programming languages which allow a value to be set to the special value NULL instead of the usual possible values of the data type.


1 Answers

Here is the code I use:

Type GetNullableType(Type type) {     // Use Nullable.GetUnderlyingType() to remove the Nullable<T> wrapper if type is already nullable.     type = Nullable.GetUnderlyingType(type) ?? type; // avoid type becoming null     if (type.IsValueType)         return typeof(Nullable<>).MakeGenericType(type);     else         return type; } 
like image 89
Alex Lyman Avatar answered Sep 27 '22 22:09

Alex Lyman