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?

2

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

Comments

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.

2 Comments

"...even though null is represented by the value 0" What do you mean? This is incorrect.
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".

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.