Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nullable type is not a nullable type?

I was doing some testing with nullable types, and it didn't work quite as I expected:

int? testInt = 0; Type nullableType = typeof(int?); Assert.AreEqual(nullableType, testInt.GetType()); // not the same type 

This doesn't work either:

DateTime? test = new DateTime(434523452345); Assert.IsTrue(test.GetType() == typeof(Nullable)); //FAIL   DateTime? test = new DateTime(434523452345); Assert.IsTrue(test.GetType() == typeof(Nullable<>)); //STILL FAIL 

My question is why does testInt.GetType() return int, and typeof(int?) return the true nullable type?

like image 820
Blake Pettersson Avatar asked Apr 24 '09 10:04

Blake Pettersson


People also ask

What is non-nullable type in C#?

Some languages have non-nullable reference types; if you want to represent a null, you use a different data type (equivalent to option<string> found in many languages), so you communicate and enforce null-checking through the type system at compile time.

Which statement is true about nullable type?

Characteristics of Nullable TypesNullable 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 !=

What are nullable data types?

The Nullable type allows you to assign a null value to a variable. Nullable types introduced in C#2.0 can only work with Value Type, not with Reference Type. The nullable types for Reference Type is introduced later in C# 8.0 in 2019 so that we can explicitly define if a reference type can or can not hold a null value.

Can nullable be null C#?

Nullable is a term in C# that allows an extra value null to be owned by a form. We will learn in this article how to work with Nullable types in C#. In C#, We have majorly two types of data types Value and Reference type. We can not assign a null value directly to the Value data type.


1 Answers

According to the MSDN :

Calling GetType on a Nullable type causes a boxing operation to be performed when the type is implicitly converted to Object. Therefore GetType always returns a Type object that represents the underlying type, not the Nullable type.

When you box a nullable object, only the underlying type is boxed.

Again, from MSDN :

Boxing a non-null nullable value type boxes the value type itself, not the System.Nullable that wraps the value type.

like image 159
Romain Verdier Avatar answered Sep 18 '22 18:09

Romain Verdier