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?
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.
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.
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.
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.
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; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With