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