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