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.
It's a negation or "not" operator. In practice ! number means "true if number == 0, false otherwise." Google "unary operators" to learn more.
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.
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 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 !
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:
ArgumentNullException
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.)If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With