System.ArgumentNullException
An ArgumentNullException is thrown when a method receives null for a parameter that does not accept it. The message tells you which one: Value cannot be null. (Parameter 'source'). The name is also available in the ParamName property.
Many .NET methods throw it, and you should throw it yourself from methods that cannot work with null. It inherits from ArgumentException. Unlike a NullReferenceException, it is thrown on purpose, and it points at the caller that passed the null, not at a bug inside the method.
Minimum version: >= 1.1 >= Core 1.0
Statistics
Common causes
The exception tells you that someone passed null. These are the usual ways it happens.
Passing null to a .NET method
Many framework methods reject null arguments. string.Join, Path.Combine, the File methods and the StreamReader constructor are some of them.
IEnumerable<string> names = null;
var joined = string.Join(", ", names); // ArgumentNullException (Parameter 'values')
Pass an empty collection instead of null:
IEnumerable<string> names = null;
var joined = string.Join(", ", names ?? Array.Empty<string>());
A null LINQ source
LINQ methods are extension methods, so calling them on a null collection does not throw a NullReferenceException. It throws an ArgumentNullException with the parameter name source.
List<Customer> customers = null;
var active = customers.Where(c => c.Id > 0).ToList(); // ArgumentNullException (Parameter 'source')
Make sure the collection exists before you query it:
List<Customer> customers = null;
var active = (customers ?? new List<Customer>()).Where(c => c.Id > 0).ToList();
A missing setting that is passed on
A value from configuration, a query string or a form field can be null when it is not set. If it is passed straight to a method that needs a value, the exception is thrown there.
var url = configuration["ApiUrl"]; // null when the setting is missing
var uri = new Uri(url); // ArgumentNullException (Parameter 'uriString')
Check the value where you read it, and fail with a message that says what is wrong:
var url = configuration["ApiUrl"]
?? throw new InvalidOperationException("ApiUrl is missing.");
var uri = new Uri(url);
The caller passed null to your own method
If the exception comes from a guard clause in your own code, the guard is doing its job. The bug is in the caller, which is the second line of the stack trace.
public class Processor
{
public void Process(Order order)
{
ArgumentNullException.ThrowIfNull(order);
// ...
}
}
Fix the caller, and decide what should happen when the value is missing:
var order = FindOrder(42);
if (order is null)
{
Console.WriteLine("Order 42 does not exist.");
return;
}
How to fix it and prevent it
Throwing the exception yourself, early and with the parameter name, makes the bug show up where the null enters.
Add guard clauses
Start every public method that cannot handle null with ArgumentNullException.ThrowIfNull. For strings, ArgumentException.ThrowIfNullOrEmpty also rejects empty values. Both are available in .NET 7 and later.
public void Send(Customer customer, string message)
{
ArgumentNullException.ThrowIfNull(customer);
ArgumentException.ThrowIfNullOrEmpty(message);
// customer and message are safe to use from here
}
Use throw expressions on older frameworks
Before .NET 6, throw the exception yourself and pass the parameter name with nameof, so the name stays correct when the parameter is renamed. A throw expression keeps constructors short.
public interface IEmailSender { }
public class ReportService
{
private readonly IEmailSender _sender;
public ReportService(IEmailSender sender)
{
_sender = sender ?? throw new ArgumentNullException(nameof(sender));
}
}
Return empty collections, not null
Methods that return collections should return an empty one when there is nothing to return. Callers can then pass the result on to LINQ and string.Join without checking it.
public IReadOnlyList<Customer> FindCustomers(string name)
{
return customers.Where(c => c.Name == name).ToList();
}
Turn on nullable reference types
With nullable reference types, the compiler warns when a value that can be null is passed to a parameter that does not accept it.
static string Join(IEnumerable<string>? names)
{
return string.Join(", ", names); // warning CS8604: Possible null reference argument for parameter 'values'.
}
How to find where the null came from
The message names the parameter, and the stack trace shows who passed the null. The first lines are usually inside the framework, where the argument was checked. The first line in your own code is the caller:
System.ArgumentNullException: Value cannot be null. (Parameter 'source')
at System.Linq.ThrowHelper.ThrowArgumentNullException(ExceptionArgument argument)
at System.Linq.Enumerable.Where[TSource](IEnumerable`1 source, Func`2 predicate)
at Shop.Services.CustomerService.GetActive(List`1 customers) in C:\src\Shop\Services\CustomerService.cs:line 9
at Program.<Main>$(String[] args) in C:\src\Shop\Program.cs:line 4
Here the parameter is source of Enumerable.Where, and the first line in the application is CustomerService.GetActive, where the collection was null. The next line shows who called it. Follow the null backwards from there.
Should you catch it?
Usually not. A null argument is a bug in the caller, and catching the exception hides it. Validate input at the edges of your application, such as controllers, and return a clear error to the client instead.
If you catch it to add context, log the parameter name and rethrow with throw;, so the original stack trace is kept.
try
{
Send(null, "hello");
}
catch (ArgumentNullException e)
{
logger.LogError(e, "Missing argument {Parameter}", e.ParamName);
throw;
}
Find ArgumentNullException before your users do
elmah.io logs every unhandled exception in your .NET application with its stack trace and request details, groups identical errors and notifies you when a new one appears.
Start free trialRelated exceptions
- NullReferenceException is thrown when code uses a null reference, for example by calling a method on it.
- ArgumentException is the base class, and is thrown when an argument is invalid for other reasons than being null.
ArgumentOutOfRangeExceptionis thrown when an argument is outside the range a method accepts.
Frequently asked questions
What does "Value cannot be null. (Parameter ...)" mean?
A method received null for the parameter named in the message, and that parameter does not accept null. The name is also in the ParamName property of the exception.
What is the difference between ArgumentNullException and NullReferenceException?
An ArgumentNullException is thrown on purpose by a method that checks its arguments. A NullReferenceException is thrown when code uses a null reference, for example by calling a method on it. The first points at the caller, the second at a line in the method that failed.
Should I use ThrowIfNull or throw the exception myself?
Use ArgumentNullException.ThrowIfNull in .NET 6 and later. It picks up the parameter name from the argument expression. On older frameworks, throw new ArgumentNullException(nameof(parameter)).
Do all methods need to validate their arguments?
Validate at the edges: public methods in libraries, and entry points of your application. Inside your own code, nullable reference types document and enforce which parameters accept null, so you do not need a guard in every method.
Let your AI agent track it down
Connect Claude Code, Cursor, VS Code or Visual Studio to the elmah.io MCP server and ask your agent to look into ArgumentNullException for you. For example:
The agent reads the stack trace and request details from elmah.io, finds the code in your repository and proposes a fix. In Claude Code, add the server with one command:
claude mcp add --transport http --client-id claudecode elmahio https://mcp.elmah.io/mcp
The MCP server is included on every plan and is currently in beta. Set up the MCP server.
Further reading
YouTube videos
Answers from Stack Overflow
It seams all you want to do is filter your context.Books by some criteria.
IEnumerable<Book> books = context.Books.Where(b => someConditions);
If you still need the empty IEnumerable you can just call Enumerable.Empty():
IEnumerable<Book> books = Enumerable.Empty<Book>();
By Rodrigo López. Read the original answer on Stack Overflow.
I'm answering my own question.
I tried adding following in my web.config
<system.serviceModel>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true" />
</system.serviceModel>
Also decorated my Service with following attribute
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Required)]
public class CalculatorService : ICalculatorSession
{
// Implement calculator service methods
}
Still no use. Then I got the solution here by which you can use Elmah without HTTPContext. i.e. log errors by writing
Elmah.ErrorLog.GetDefault(null).Log(new Error(ex));
instead of
Elmah.ErrorSignal.FromCurrentContext().Raise(error);
By IsmailS. Read the original answer on Stack Overflow.
Try both Model != null and !String.IsNullOrEmpty(Model.ImageName) first, as you may be passing not only a Null value from the Model but also a Null Model:
@if (Model != null && !String.IsNullOrEmpty(Model.ImageName))
{
<label for="Image">Change picture</label>
}
else
{
<label for="Image">Add picture</label>
}
Otherwise, you can make it even neater with some ternary fun! - but that will still error if your model is Null.
<label for="Image">@(String.IsNullOrEmpty(Model.ImageName) ? "Add" : "Change") picture</label>
By naspinski. Read the original answer on Stack Overflow.
The NotNullAttribute is gone. It was replaced with conditionally throwing ArgumentNullException and subsequently removed by the ASP.NET team. As of Jan 12, 2016 there's no plan to bring it back. (At that time, I was working on the ASP.NET team.)
The attribute will be replaced through a pre-compilation step, using Roslyn, by code that does the actual check.
However, the feature is not yet ready as of Jun 17, 2015. It will come in a later version. So far, it is just an empty internal attribute that should be implemented in each project again:
[AttributeUsage(AttributeTargets.Parameter, AllowMultiple = false)]
internal sealed class NotNullAttribute : Attribute
{
}
By Victor Hurdugaci. Read the original answer on Stack Overflow.
Thanks everyone, here is my ErrorHelper class I came up with to manually log errors on websites and in WCF services, windows services, etc:
public static class ErrorHelper
{
/// <summary>
/// Manually log an exception to Elmah. This is very useful for the agents that try/catch all the errors.
///
/// In order for this to work elmah must be setup in the web.config/app.config file
/// </summary>
/// <param name="ex"></param>
public static void LogErrorManually(Exception ex)
{
if (HttpContext.Current != null)//website is logging the error
{
var elmahCon = Elmah.ErrorSignal.FromCurrentContext();
elmahCon.Raise(ex);
}
else//non website, probably an agent
{
var elmahCon = Elmah.ErrorLog.GetDefault(null);
elmahCon.Log(new Elmah.Error(ex));
}
}
}
By jhilden. Read the original answer on Stack Overflow.
Source: Stack Overflow