Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does exclamation mark mean before invoking a method in C# 8.0? [duplicate]

I have found a code written in C# seemingly version 8.0. In the code, there is an exclamation mark before invoking a method. What does this part of the code mean, and above all, what are its uses?

var foo = Entity!.DoSomething(); 
like image 784
icn Avatar asked Dec 07 '19 21:12

icn


People also ask

What does '!' Mean in C programming?

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

Why exclamation mark is used in C language?

“exclamation mark in c” Code Answer The negation operator (!) simply just reverses the meaning of its operand.


2 Answers

This would be the null forgiving operator.
It tells the compiler "this isn't null, trust me", so it does not issue a warning for a possible null reference.

In this particular case it tells the compiler that Entity isn't null.

like image 200
Mor A. Avatar answered Oct 22 '22 17:10

Mor A.


! is the Null-Forgiving Operator. To be specific it has two main effects:

  • it changes the type of the expression (in this case it modifies Entity) from a nullable type into a non-nullable type; (for example, object? becomes object)

  • it suppresses nullability related warnings, which can hide other conversions

This seems to come up particularly with type parameters:

IEnumerable<object?>? maybeListOfMaybeItems = new object[] { 1, 2, 3 };  // inferred as IEnumerable<object?> var listOfMaybeItems = maybeListOfMaybeItems!;  // no warning given, because ! supresses nullability warnings IEnumerable<object> listOfItems = maybeListOfMaybeItems!;  // warning about the generic type change, since this line does not have ! IEnumerable<object> listOfItems2 = listOfMaybeItems; 
like image 40
Dave Cousineau Avatar answered Oct 22 '22 16:10

Dave Cousineau