0

I saw the following code in my project.

public virtual Department Department { get; set; } = null!;

I'm not sure what it means about null!. Does it mean null or not null or it's just null for sure or the ! simply ignore the compiler warning? Can anyone explain?

Son of Man
  • 1,213
  • 2
  • 7
  • 27
Will Huang
  • 2,955
  • 2
  • 37
  • 90
  • 1
    [null forgiving operator](https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/null-forgiving) – Mikael Apr 19 '23 at 01:42
  • 1
    The internet has search tools. If I search for `c# null!`, the first two links I see are: https://stackoverflow.com/questions/54724304/what-does-null-statement-mean and https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/null-forgiving – Flydog57 Apr 19 '23 at 03:19

2 Answers2

1

Here is the documentation about the bang operator. TLDR the default value is null and its telling the compiler its okay.

Will
  • 26
  • 1
  • 4
0

In C#, null means "no object." You cannot use 0 instead of null in your programs even though null is represented by the value 0. You can use null with any reference type including arrays, strings, and custom types. In C#, null is not the same as the constant zero.

The difference between “is not null” and “!= null” is that the compiler guarantees that no user-overloaded operator is called when using “is not null” instead of “!= null” (or “is null” instead of “== null”).

The null-forgiving operator (!) is used to inform the compiler that passing null is expected and shouldn’t be warned about. You can also use the null-forgiving operator when you definitely know that an expression can’t be null but the compiler doesn’t manage to recognize that.

  • 1
    "...even though null is represented by the value 0" What do you mean? This is incorrect. – gunr2171 Apr 19 '23 at 02:38
  • Your first two paragraphs are not relevant to the question at all. The question asks "what does the exclamation mark mean after the `null` keyword?". Providing a background of what null is isn't necessary. Comparison to null (`is not null` vs `!= null`) isn't needed either because the OP incorrectly assumes the `!` relates to "not". – gunr2171 Apr 19 '23 at 02:40