Home > Backend Development > C++ > What Does the `!` (Null-Forgiving) Operator Mean in C# 8.0?

What Does the `!` (Null-Forgiving) Operator Mean in C# 8.0?

Patricia Arquette
Release: 2025-01-09 10:16:45
Original
978 people have browsed it

What Does the `!` (Null-Forgiving) Operator Mean in C# 8.0?

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>
Copy after login

Difference between the first and second lines

  • First line: The LastName property is nullable, allowing it to hold a null value, represented by the ? operator.
  • Second line: 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

  • Avoid overuse: The null-tolerant operator should be used with caution, as it defeats the purpose of null-safety.
  • Runtime Exceptions: The ! operator only disables compiler-level checks; if the value is null, runtime exceptions may still occur.
  • Valid use cases: Despite its limitations, the null-tolerant operator is used when the compiler cannot infer the nullability of a value, when migrating legacy code, or when testing the behavior of code when handling null Might be helpful.

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template