Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How is it that can I execute method on int? set to null without NullReferenceException?

Tags:

c#

nullable

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?

like image 500
Buda Gavril Avatar asked Jan 24 '17 19:01

Buda Gavril


People also ask

How do you avoid null reference exception?

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.

How do I fix NullReferenceException in C#?

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.

How do I fix this error system NullReferenceException object reference not set to an instance of an object?

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.


2 Answers

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

like image 51
Eugene Podskal Avatar answered Oct 21 '22 21:10

Eugene Podskal


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.

like image 39
Janne Matikainen Avatar answered Oct 21 '22 21:10

Janne Matikainen