Редактиране

Reference types (C# reference)

C# has two kinds of types: reference types and value types. Variables of reference types store references to their data (objects), while variables of value types directly contain their data. With reference types, two variables can reference the same object. Therefore, operations on one variable can affect the object referenced by the other variable. With value types, each variable has its own copy of the data. Operations on one variable can't affect the other variable, except in the case of in, ref, and out parameter variables. For more information, see in, ref, and out parameter modifier.

The C# language reference documents the most recently released version of the C# language. It also contains initial documentation for features in public previews for the upcoming language release.

The documentation identifies any feature first introduced in the last three versions of the language or in current public previews.

Tip

To find when a feature was first introduced in C#, consult the article on the C# language version history.

Use the following keywords to declare reference types:

C# also provides the following built-in reference types:

Nullable reference types

In a nullable-aware context, reference types can be non-nullable or nullable:

  • A non-nullable reference type (T) indicates that a variable isn't intended to hold null. The compiler issues warnings if a non-nullable reference might be dereferenced when it could be null, or if you assign null to it.
  • A nullable reference type (T?) indicates that a variable can hold null. You append the ? suffix to the type name to declare that the variable might be null.

Unlike nullable value types, which wrap an underlying value type in the Nullable<T> struct at run time, nullable reference types are compile-time annotations enforced by compiler static flow analysis. At run time, both string and string? are represented by the same underlying type, String. For more information, see Nullable reference types.

See also