Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Type checking on Nullable<int>

Tags:

c#

If have the following method:

static void DoSomethingWithTwoNullables(Nullable<int> a, Nullable<int> b)
{
    Console.WriteLine("Param a is Nullable<int>: " + (a is Nullable<int>));
    Console.WriteLine("Param a is int          : " + (a is int));
    Console.WriteLine("Param b is Nullable<int>: " + (b is Nullable<int>));
    Console.WriteLine("Param b is int          : " + (b is int));
}

When i call this method with null as a parameter, the type check returns false for this parameter. For example this code

DoSomethingWithTwoNullables(5, new Nullable<int>());

results in this output:

Param a is Nullable<int>: True
Param a is int          : True
Param b is Nullable<int>: False
Param b is int          : False

Is there any way to preserve the type information when using a Nullable and passing null? I know that checking the type in this example is useless, but it illustrates the problem. In my project, I pass the parameters to another method that takes a params object[] array and tries to identify the type of the objects. This method needs to do different things for Nullable<int> and Nullable<long>.

like image 313
bernd_rausch Avatar asked Oct 15 '12 13:10

bernd_rausch


People also ask

Is nullable int a value type?

Nullable types are neither value types nor reference types. They are more like value types, but have a few properties of reference types. Naturally, nullable types may be set to null . Furthermore, a nullable type cannot satisfy a generic struct constraint.

How do you check if a nullable is null?

Characteristics of Nullable Types Nullable types can only be used with value types. The Value property will throw an InvalidOperationException if value is null; otherwise it will return the value. The HasValue property returns true if the variable contains a value, or false if it is null. You can only use == and !=

Does HasValue check for null?

HasValue: This property returns a bool value based on that if the Nullable variable has some value or not. If the variable has some value, then it will return true; otherwise, it will return false if it doesn't have value or it's null.


1 Answers

Going straight to the underlying problem, no, you can't do this. A null Nullable<int> has exactly the same boxed representation as a null Nullable<long>, or indeed a 'normal' null. There is no way to tell what 'type' of null it is, since its underlying representation is simply all-zeros. See Boxing Nullable Types for more details.

like image 111
thecoop Avatar answered Oct 01 '22 05:10

thecoop