C# 8.0 introduced nullable reference types, enabling the compiler to warn about potential null reference exceptions. However, sometimes you know a value isn't null even when the compiler cannot prove it, such as after validation checks or in test scenarios.
The null-forgiving operator !
tells the compiler to suppress nullable warnings for a specific expression, asserting that the value is not null despite what static analysis suggests.
Code
C#
string? GetName() => GetUserInput();
void Process()
{
string? name = GetName();
if (string.IsNullOrEmpty(name))
return;
// Compiler still thinks name might be null
Console.WriteLine(name!.ToUpper()); // ! suppresses warning
}
// In unit tests
[Test]
public void TestMethod()
{
var result = repository.Find(id);
Assert.NotNull(result);
// We know it's not null after the assertion
Assert.Equal("Expected", result!.Name);
}
C#
string GetName() => GetUserInput();
void Process()
{
string name = GetName();
if (string.IsNullOrEmpty(name))
return;
// No warning, but also no null safety
Console.WriteLine(name.ToUpper());
}
// In unit tests
[Test]
public void TestMethod()
{
var result = repository.Find(id);
Assert.NotNull(result);
// No null-safety analysis at all
Assert.Equal("Expected", result.Name);
}
Notes
- The
!
operator has no effect at runtime - it only suppresses compiler warnings - Use sparingly and only when you're certain a value isn't null
- Common scenarios include: after explicit null checks the compiler can't understand, following assertions in tests, or when working with legacy code
- Overuse can defeat the purpose of nullable reference types and hide real bugs
- Also called the "null-suppression operator" or "dammit operator"