Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a reason why NullReferenceException does not give the name of the variable?

Tags:

.net

exception

The ArgumentNullException has a ParamName property to indicate which argument was passed as null.

Why does the NullReferenceException not have a similar property? Would it have been technically possible to implement within .Net?

like image 210
David Neale Avatar asked Mar 10 '11 09:03

David Neale


People also ask

How do I fix 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.

What does system NullReferenceException mean?

A NullReferenceException exception is thrown when you try to access a member on a type whose value is null . A NullReferenceException exception typically reflects developer error and is thrown in the following scenarios: You've forgotten to instantiate a reference type.

Can an object reference be null?

So, a reference is what a variable of a reference type contains. These variables can point to “nothing”, though, and that's what we call a null reference: a reference that doesn't point to any object. When you try to call a method or another member on the said variable, you got the NullReferenceException.


1 Answers

A NullReferenceException is thrown by the CLR when it tries to navigate a null reference. This isn't necessarily associated with a variable, and in particular the CLR really doesn't care where it came from - it's just a value on the stack.

Compare that with ArgumentNullException which is explicitly thrown via code such as:

if (foo == null)
{
    throw new ArgumentNullException("foo");
}

There's no magic here - and you can even give the wrong name if you want. So they're really very different situations.

like image 57
Jon Skeet Avatar answered Sep 25 '22 03:09

Jon Skeet