Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Structure types: moved an example for clarity #22230

Merged
merged 1 commit into from Jan 7, 2021
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
10 changes: 5 additions & 5 deletions docs/csharp/language-reference/builtin-types/struct.md
Expand Up @@ -24,11 +24,7 @@ Because structure types have value semantics, we recommend you to define *immuta

## `readonly` struct

Beginning with C# 7.2, you use the `readonly` modifier to declare that a structure type is immutable:

[!code-csharp[readonly struct](snippets/shared/StructType.cs#ReadonlyStruct)]

All data members of a `readonly` struct must be read-only as follows:
Beginning with C# 7.2, you use the `readonly` modifier to declare that a structure type is immutable. All data members of a `readonly` struct must be read-only as follows:

- Any field declaration must have the [`readonly` modifier](../keywords/readonly.md)
- Any property, including auto-implemented ones, must be read-only. In C# 9.0 and later, a property may have an [`init` accessor](../../whats-new/csharp-9.md#init-only-setters).
Expand All @@ -38,6 +34,10 @@ That guarantees that no member of a `readonly` struct modifies the state of the
> [!NOTE]
> In a `readonly` struct, a data member of a mutable reference type still can mutate its own state. For example, you can't replace a <xref:System.Collections.Generic.List%601> instance, but you can add new elements to it.

The following code defines a `readonly` struct with init-only property setters, available in C# 9.0 and later:

[!code-csharp[readonly struct](snippets/shared/StructType.cs#ReadonlyStruct)]

## `readonly` instance members

Beginning with C# 8.0, you can also use the `readonly` modifier to declare that an instance member doesn't modify the state of a struct. If you can't declare the whole structure type as `readonly`, use the `readonly` modifier to mark the instance members that don't modify the state of the struct.
Expand Down