Why is ArgumentNullException? Why not a System.NullReferenceException?

See the line of code below:

DataTable [] _tables = null; // Throws System.NullReferenceException _tables.GetType(); // Throws System.ArgumentNullException _tables.Count(); 

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

+8
c # nullreferenceexception argumentexception
source share
4 answers

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

 Enumerable.Count(_tables); 

... therefore _tables is an argument to the method, and it makes sense for the exception to tell you this. You do not dereference the _tables variable _tables you call Count() , while you call GetType .

+20
source share

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

 System.Linq.Enumerable.Count(_tables); 

If you do not want to use the extension method: use _tables.Length .

+7
source share

Count() is an extension method (therefore, it should call ArgumentNullException if the passed value is null and null is illegal), and not an object instance method, that is, Count is defined as public static int Count<T>(this IEnumerable<T> source)

+4
source share

Because it is an extension method, not an instance method.

Since it is compiled into Enumerable.Count(_tables) , it does not apply to a NullReferenceException , so it just throws an ArgumentNullException . However, GetType is an instance method, so you are trying to call the method on null , which ... um does not work.

+4
source share

All Articles