Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does some methods work while some do not on null values of nullable structs?

Straight to the point:

int? i = null;
i.ToString(); //happy
i.GetType(); //not happy

I get a very related question which actually deals on why does i.ToString() work fine.

Edit: Just found out this corner case has been the most voted one in this SO thread!

like image 927
nawfal Avatar asked Oct 14 '12 20:10

nawfal


People also ask

Can struct be assigned to null?

11), it is not possible for values of a struct type to be null . the output is 10 . The assignment of a to b creates a copy of the value, and b is thus unaffected by the assignment to a.x .

Why we use nullable types in C#?

We are using nullable types when we need to represent an undefined value of an underlying type. While Boolean values can have either true or false values, a null in this case means false as there is no undefined value. When you have a database interaction, a variable value can be either undefined or missing.

Can we assign null to struct in C#?

You can't assign null to an element of the list because structs are value types, while null means an empty pointer, and so can only be assigned to reference type variables.


2 Answers

It is because ToString is virtual while GetType is not. Nullables have special boxing behavior in the CLR. When you call GetType on a nullable it is boxed (see MSDN, actually this happens for any struct). However, with a nullable, the the underlying value is boxed, not the actual nullable. ToString on the other hand calls the override of ToString method on Nullable<T>. Also, I would note that int? i = null is syntax sugar for Nullable<int> i = new Nullable<int>(). So, there really is an object in your variable i.

like image 55
Mike Zboray Avatar answered Oct 25 '22 11:10

Mike Zboray


Why does i.ToString() not fail?

Use any .NET decompiler and look at the Nullable<T> class. You'll see that ToString() is overriden as follows:

public override string ToString()
{
  if (!this.HasValue)
    return "";
  else
    return this.value.ToString();
}

Why does i.GetType() fail?

See mike z's answer.

like image 45
Cristian Lupascu Avatar answered Oct 25 '22 10:10

Cristian Lupascu