Postfix ! (exclamation) operator in C# [duplicate]

This is the null-forgiving operator (also known as the “damn-it” operator) in C# 8, which effectively tells the compiler to assume that the value will be non-null. It’s a little like a cast, in terms of telling the compiler that you know better than it does – but it has no effect at execution time, so you’re effectively bypassing the safety of the compiler checks.

It’s introduced as part of the C# 8 nullable-reference type feature. It is available in public preview builds of .NET Core 3.0 SDK.

Typical uses in my experience:

  • Testing your argument validation code, to prove that if you do pass null into a method, you’ve got validation to throw ArgumentNullException
  • Places where you’re certain the value won’t be null due to other invariants that the compiler isn’t aware of. (For example, in Noda Time I have a ParseResult<T> which has fields of a value and an exception provider. Either the exception provider is null or the value is null, but never both, and I always check the exception provider before using the value.)

Leave a Comment