Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why ArgumentNullException? Why not System.NullReferenceException?

See line of code below:

DataTable [] _tables = null;

// Throws System.NullReferenceException
_tables.GetType();

// Throws System.ArgumentNullException
_tables.Count();

In this lines of code I have _tables reference and trying to access its system define functions GetType() and Count(), both throw exception but why .Count() throws System.ArgumentNullException, since we have same value for reference which is null?

like image 202
Ankush Madankar Avatar asked Aug 09 '13 11:08

Ankush Madankar


People also ask

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.

What is System ArgumentNullException?

An ArgumentNullException exception is thrown when a method is invoked and at least one of the passed arguments is null but should never be null .

What is System NullReferenceException?

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.


2 Answers

Count() is an extension method on IEnumerable<T>, declared in System.Linq.Enumerable - so you're actually calling:

Enumerable.Count(_tables);

... so _tables is a method argument, and it makes sense for the exception to tell you that. You're not actually dereferencing the _tables variable when you call Count(), whereas you are when you call GetType.

like image 112
Jon Skeet Avatar answered Nov 15 '22 20:11

Jon Skeet


Because Count here is a call to an extension-method with _tables as the argument - it is actually:

System.Linq.Enumerable.Count(_tables);

If you don't want to use the extension method: use _tables.Length.

like image 32
Marc Gravell Avatar answered Nov 15 '22 19:11

Marc Gravell