Search code examples
c#nullreferenceexceptionargumentexception

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?


Solution

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