7

This is my very first question here. I bumped into a method like this in C#:

void Do(string action!) { ... }

And don't get what the ! after action is and it does. Can you help me understand it?

Majid Parvin
  • 4,499
  • 5
  • 29
  • 47

2 Answers2

9

This is named the bang operator, !, which can be positioned after any identifier in a parameter list and this will cause the C# compiler to emit standard null checking code for that parameter. For example:

void Do(string action!) { ... }

Will be translated into:

void Do(string action!) {
    if (action is null) {
        throw new ArgumentNullException(nameof(action));
    }
    ...
}

btw, at the moment, this feature is not available yet. You can find more info here.

Majid Parvin
  • 4,499
  • 5
  • 29
  • 47
3

https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/null-forgiving

you use the null-forgiving operator to declare that expression x of a reference type isn't null

  • This is illegal in the example the OP gave (on a parameter). – Yair Halberstadt Apr 08 '21 at 09:52
  • @YairHalberstadt in this time of writing, the linked article explain both scenarios - one which is equivalent to what OP asked for and the other is when you know an expression cannot be null, e.g. (as taken from the link): `null!` and `p!.Name` – gimlichael Oct 02 '22 at 20:32