Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

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.

like image 640
Vladislav Rishe Avatar asked Sep 02 '19 11:09

Vladislav Rishe


People also ask

What does '!' Mean in C?

It's a negation or "not" operator. In practice ! number means "true if number == 0, false otherwise." Google "unary operators" to learn more.

What does exclamation mean C#?

This is called the null-forgiving operator and is available in C# 8.0 and later. It has no effect at run time, only at compile time. Its purpose is to inform the compiler that some expression of a nullable type isn't null, to avoid possible warnings about null references.

What does exclamation mark after variable mean?

The exclamation mark (non-null assertion) operator removes null and undefined from the type of an expression. It is used when we we know that a variable that TypeScript thinks could be null or undefined actually isn't.

What is '!' In TypeScript?

What is the TypeScript exclamation mark? The non-null assertion operator tells the TypeScript compiler that a value typed as optional cannot be null or undefined . For example, if we define a variable as possibly a string or undefined, the !


1 Answers

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.)
like image 125
Jon Skeet Avatar answered Oct 15 '22 14:10

Jon Skeet