문제

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?

도움이 되었습니까?

해결책

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.

다른 팁

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.

Because it's an extension method, and not an instance method.

As it's compiled to Enumerable.Count(_tables), it doesn't apply to NullReferenceException, so it just throws an ArgumentNullException instead. However, GetType is an instance method, so you are trying to call a method on null, which... um, doesn't work.

Count() is an extension method (it should therefore throw an ArgumentNullException if a passed in value is null and null is illegal), not a method on the instance of the object i.e. Count is defined as public static int Count<T>(this IEnumerable<T> source).

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top