System.ArgumentNullException: Value cannot be null. (Parameter 'source')
System.ArgumentNullException: Value cannot be null. (Parameter 'key')
A method received null for a parameter that doesnβt accept it.
Fix 1: LINQ on Null Collection
// β Calling LINQ on null
List<string> items = null;
var count = items.Where(x => x.Length > 3).Count(); // π₯
// β
Initialize or check
List<string> items = new List<string>();
// Or
var count = items?.Where(x => x.Length > 3).Count() ?? 0;
Fix 2: Dictionary Null Key
// β Null key
string key = null;
dict[key] = "value"; // π₯
// β
Check for null
if (key != null) dict[key] = "value";
Fix 3: Dependency Injection Not Registered
// β Service not registered in DI container
public class MyController {
public MyController(IMyService service) { } // π₯ null if not registered
}
// β
Register in Program.cs
builder.Services.AddScoped<IMyService, MyService>();
Fix 4: Configuration Value Missing
// β Config key doesn't exist
var connString = Configuration.GetConnectionString("Default");
new SqlConnection(connString); // π₯ If null
// β
Validate
var connString = Configuration.GetConnectionString("Default")
?? throw new InvalidOperationException("Connection string 'Default' not found");
Fix 5: Guard Clauses
// β
Fail fast with clear messages
public void Process(string input) {
ArgumentNullException.ThrowIfNull(input); // C# 10+
// Or
if (input is null) throw new ArgumentNullException(nameof(input));
}