39

The last day I was exploring .NET sources on GitHub and stumbled upon the following construct: ((SomeTypeToCast)variable!).SomeMethodToCall().

Please, notice the postfix ! which is oroginally listed here

So, the simple question: what's this?

P.S.: Personally I've got a couple surmises on what this thing may mean: kind of "this value is never null". However there is no such operator in C# (at least publicly available) and such expression fails to compile when I'm trying it in test project myself.

Vladislav Rishe
  • 691
  • 1
  • 6
  • 8

1 Answers1

65

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.)
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194