null!
Meaning of operator
In C# 8.0 and its nullable reference types feature, the !
operator has a new purpose, called the "null-tolerant operator". When applied to a type, this operator overrides the nullability of the value, making it non-nullable, meaning that although nullable by default, null is treated as a "non-null" type.
Practical example
Consider a class where LastName
properties are nullable and MiddleName
properties are non-nullable:
<code class="language-csharp">public class Person { public string? LastName { get; set; } public string MiddleName { get; set; } = null!; }</code>
Difference between the first and second lines
LastName
property is nullable, allowing it to hold a null value, represented by the ?
operator. MiddleName
attributes are non-nullable, represented by !
. This means it cannot hold null values. However, the null!
expression explicitly overrides this non-nullability and treats null as a non-null value. Technical explanation
C# 8.0 introduced "null safety", where all reference types are non-nullable by default. To represent a nullable type, the ?
operator must be used. Conversely, the !
operator can be applied to nullable types to indicate non-nullability.
Notes
!
operator only disables compiler-level checks; if the value is null, runtime exceptions may still occur. The above is the detailed content of What Does the `!` (Null-Forgiving) Operator Mean in C# 8.0?. For more information, please follow other related articles on the PHP Chinese website!