💪 Suppress Null Warnings When Certain
Nullable Reference Types help, but sometimes compiler is wrong. Null Forgiving Operator (!) tells compiler “I know it’s not null”. Use sparingly.
📝 Basic Usage
// Compiler warning: Possible null reference
string? maybeNull = GetValue();
int length = maybeNull.Length; // Warning!
// Tell compiler: "I know it's not null"
int length = maybeNull!.Length; // No warning
// In method calls
ProcessValue(maybeNull!);
// In constructors (initializing non-nullable after validation)
public class Person
{
public string Name { get; }
public Person(string? name)
{
if (string.IsNullOrEmpty(name))
throw new ArgumentException();
Name = name!; // We validated, safe to assign
}
}
🎯 Real-World Examples
// Dictionary lookup (you know key exists) var dict = new Dictionary(); dict["key"] = "value"; string value = dict["key"]!; // Compiler doesn't know, but we do // After null check (compiler doesn't track flow for some cases) string? input = GetInput(); if (input is null) return; int len = input!.Length; // Still need ! even after check (sometimes) // Unit test setup public void TestMethod() { MyClass? obj = CreateInstance(); Assert.NotNull(obj); obj!.DoSomething(); // Test will fail if null anyway }
💡 When to Use
- After validation (null check done, but compiler doesn’t see)
- Unit tests (you know the value is set)
- Dependency Injection (framework guarantees non-null)
- Dictionary/Collection lookups (you know key exists)
- Interop with non-nullable frameworks
“Nullable Reference Types fixed many bugs, but sometimes compiler was wrong. Null Forgiving Operator silenced false warnings. Use carefully, but useful.”
