-
Notifications
You must be signed in to change notification settings - Fork 6k
C# 11: required members #30275
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
Merged
Merged
C# 11: required members #30275
Changes from all commits
Commits
Show all changes
16 commits
Select commit
Hold shift + click to select a range
1cd5ba3
edit pass and update samples
BillWagner 2c260ef
finish updates to properties conceptual article.
BillWagner f3d5c0f
fields article updated, placeholder for required
BillWagner 3194a41
Finish reference for `requied`
BillWagner b040f77
Update required.md
BillWagner 5f45a69
fix build warnings.
BillWagner ea5037b
Update keywords.csproj
BillWagner 2a6be84
Apply suggestions from code review
BillWagner 2cd1420
Update docs/csharp/language-reference/keywords/required.md
BillWagner 7188ae3
Update properties overview
BillWagner e08f17e
update the using properties article
BillWagner 7ff5e8f
fix properties issue.
BillWagner 84a0dda
edit more properties articles
BillWagner 2e0720e
edit how to declare properties
BillWagner 1b81c08
finish the last of the properties articles
BillWagner 9c3407d
fix snippet builds
BillWagner File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,26 @@ | ||
--- | ||
description: "required modifier - C# Reference" | ||
title: "required modifier - C# Reference" | ||
ms.date: 07/20/2022 | ||
helpviewer_keywords: | ||
- "required keyword [C#]" | ||
--- | ||
# required modifier (C# Reference) | ||
|
||
The `required` modifier indicates that the *field* or *property* it's applied to must be initialized by all constructors or using an [object initiializer](../../programming-guide/classes-and-structs/object-and-collection-initializers.md). Any expression that initializes a new instance of the type must initialize all *required members*. Constructors indicate that they initialize all required members by adding the [`SetsRequiredMembers`](../attributes/general.md#setsrequiredmembers-attribute) attribute in the constructor declaration. Code that uses a constructor without this attribute must use *object initializers* to initialize all `required` members. The `required` modifier is available beginning with C# 11. | ||
|
||
The `required` modifier and the `SetsRequiredMembers` attribute enable developers to create types where properties or fields must be properly initialized, yet still allow initialization using either constructors or object initializers. Several rules ensure this behavior: | ||
|
||
- The `required` modifier can be applied to *fields* and *properties* declared in `struct`, and `class` types, including `record` and `record struct` types. The `required` modifier can't be applied to members of an `interface`. | ||
- Explicit interface implementations can't be marked as `required`. They can't be set in object initializers. | ||
- Required members must be initialized, but they may be initialized to `null`. If the type is a non-nullable reference type, the compiler issues a warning if you initialize the member to `null`. The compiler issues an error if the member isn't initialized at all. | ||
- Required members must be at least as visible as their containing type. For example, a `public` class can't contain a `required` field that's `protected`. Furthermore, required properties must have setters (`set` or `init` accessors) that are at least as visible as their containing types. Members that aren't accessible can't be set by code that creates an instance. | ||
- Derived classes can't hide a `required` member declared in the base class. Hiding a required member prevents callers from using object initializers for it. Furthermore, derived types that override a required property must include the `required` modifier. The derived type can't remove the `required` state. Derived types can add the `required` modifier when overriding a property. | ||
- A type with any `required` members may not be used as a type argument when the type parameter includes the `new()` constraint. The compiler can't enforce that all required members are initialized in the generic code. | ||
- A constructor that chains to another constructor annotated with the `SetsRequiredMembers` attribute, either `this()`, or `base()`, must also include the `SetsRequiredMembers` attribute. That ensures that callers can correctly use all appropriate constructors. | ||
- Copy constructors generated for `record` types have the `SetsRequiredMembers` attribute applied if any of the members are `required`. | ||
- The `required` modifier isn't allowed on the declaration for positional parameters on a record. | ||
|
||
The following code shows a class hierarchy that uses the `required` modifier for the `FirstName` and `LastName` properties: | ||
|
||
:::code language="csharp" source="./snippets/RequiredExample.cs" id="SnippetRequired"::: |
34 changes: 34 additions & 0 deletions
34
docs/csharp/language-reference/keywords/snippets/RequiredExample.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,34 @@ | ||
using System.Diagnostics.CodeAnalysis; | ||
|
||
namespace RequiredMembers; | ||
|
||
// <SnippetRequired> | ||
public class Person | ||
{ | ||
public Person() { } | ||
|
||
[SetsRequiredMembers] | ||
public Person(string firstName, string lastName) => | ||
(FirstName, LastName) = (firstName, lastName); | ||
|
||
public required string FirstName { get; init; } | ||
public required string LastName { get; init; } | ||
|
||
public int? Age { get; set; } | ||
} | ||
|
||
public class Student : Person | ||
{ | ||
public Student() : base() | ||
{ | ||
} | ||
|
||
[SetsRequiredMembers] | ||
public Student(string firstName, string lastName) : | ||
base(firstName, lastName) | ||
{ | ||
} | ||
|
||
public double GPA { get; set; } | ||
} | ||
// </SnippetRequired> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
7 changes: 3 additions & 4 deletions
7
docs/csharp/programming-guide/classes-and-structs/auto-implemented-properties.md
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.