🔧 Error Fixes
· 1 min read

C# ArgumentNullException — How to Fix It


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));
}