I have read on MSDN that:
The null keyword is a literal that represents a null reference, one that does not refer to any object.
But I've seen the following code running without throwing any exception:
int? i = null;
var s = i.ToString();
So if the variable i
is null, why can I execute it's method?
Use Null Coalescing to Avoid NullReferenceExceptions It works with all nullable data types. The following code throws an exception without the null coalescing. Adding “?? new List<string>()” prevents the “Object reference not set to an instance of an object” exception.
Solutions to fix the NullReferenceException To prevent the NullReferenceException exception, check whether the reference type parameters are null or not before accessing them. In the above example, if(cities == null) checks whether the cities object is null or not.
The best way to avoid the "NullReferenceException: Object reference not set to an instance of an object” error is to check the values of all variables while coding. You can also use a simple if-else statement to check for null values, such as if (numbers!= null) to avoid this exception.
Because int?
is actually a Nullable<Int32>
and Nullable<T>
is a struct
, and a structure cannot be null.
It is just how Nullable types work. They are not reference values, so they can't be null, but they can have a state when they are considered equivalent to null.
You can get more details about Nullable<T>
implementation in how are nullable types implemented under the hood in .net? and Nullable<T> implementation
Though as pointed by @JeppeStigNielsen there is one case when you can get a NRE:
However: When boxed to a reference type, special treatment of Nullable<> ensures we do get a true null reference. So for example i.GetType() with i as in the question will blow up with the NullReferenceException. That is because this method is defined on object and not overridable
The code you pasted
int? i = null;
is actually just a shorthand for
int? i = new int?();
Which is a shorthand for
Nullable<int> i = new Nullable<int>();
Assigning null is using the implicit operator which you can read more from here MSDN.
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