50

Exploring .NET sources on GitHub I stumbled upon

((SomeTypeToCast)variable!).SomeMethodToCall()

What's this postfix !?

I surmise this is a kind of "this value is never null". However there is no such operator in C# (at least publicly available) and such an expression fails to compile when I try it in a test project.

0

1 Answer 1

78

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.)
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.