In-depth understanding of C# null! statement
The null!
statement in C# 8.0 is a powerful tool that allows developers to suppress null reference checks for specific expressions. However, before using it, it is important to understand how it works and its effects.
Null tolerance operator
Thenull!
statement uses the null-tolerant operator (!
). This operator has dual functionality depending on its context. When applied to a type, it changes the type's nullability from nullable to non-nullable. This is called the null-tolerant operator.
Suppress null checking
When applied to an expression (such as null!
), the null-tolerant operator suppresses null checking for that specific expression. This overrides the nullability of the expression, allowing it to be used as a non-nullable value for that specific operation.
Technical explanation
C# 8.0 introduces nullable reference types to improve null safety. By default, all reference types are non-nullable, which means they cannot hold null values. The ?
and !
operators can override this default.
?
operator marks a type as nullable, allowing it to hold null values. On the other hand, the !
operator marks a type as non-nullable, ensuring that it cannot hold null values.
When to use null!?
The null!
statement should be used with caution, and overuse should be avoided. It is mainly used in the following scenarios:
Example: Understanding null! Statement
In the code you provided:
FirstName { get; }
is declared as a non-nullable string, which means it cannot hold null values. LastName { get; } = null!
declares the LastName
property as non-nullable, despite initially assigning it a value of null. By using null!
you can override the default nullability and ensure that this property is treated as non-nullable. The above is the detailed content of When and Why Should You Use the C# null! Operator?. For more information, please follow other related articles on the PHP Chinese website!