
What causes the ArgumentNullException to be thrown in C# programs? This exception is not thrown by the runtime directly. Instead, it is thrown by code that detects an invalid (null) argument.
This C# article looks at places where ArgumentNullException is encountered.
The ArgumentNullException is always thrown by code that checks arguments for null and then throws it explicitly. Usually, the method would fail with a NullReferenceException if the check was removed. Here, we use a null literal on the Dictionary indexer. The indexer compiles to the get_Item method. Internally, get_Item eventually uses the statement "throw new ArgumentNullException".
Program that results in ArgumentNullException [C#]
using System.Collections.Generic;
class Program
{
static void Main()
{
var dictionary = new Dictionary<string, int>();
int value = dictionary[null];
}
}
Output
Unhandled Exception: System.ArgumentNullException: Value cannot be null.
Parameter name: key
Dictionary Examples
Indexer Examples
The ArgumentNullException can be understood as an exception that is thrown by user code, not the runtime. It thus represents an error that was carefully added to help the users of the library better understand what is wrong. In many cases, avoiding the null check and allowing the runtime itself to detect a NullReferenceException would yield better performance, at the cost of understandability.
We saw a program that throws the ArgumentNullException by passing a null reference to an indexer method. An ArgumentNullExceptions helps you understand what went wrong when calling a method, and provides a very clear hint as to how you can correct it—check for null.
Null Tips ArgumentException Exception Handling