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?
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.
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 !=
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.
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.
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.
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