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