diff --git a/docs/csharp/language-reference/compiler-messages/cs9036.md b/docs/csharp/language-reference/compiler-messages/cs9036.md new file mode 100644 index 0000000000000..fe6f3a4c5b004 --- /dev/null +++ b/docs/csharp/language-reference/compiler-messages/cs9036.md @@ -0,0 +1,67 @@ +--- +description: "Compiler Error CS9036" +title: "Compiler Error CS9036" +ms.date: 05/19/2025 +ai-usage: ai-generated +f1_keywords: + - "CS9036" +helpviewer_keywords: + - "CS9036" +--- +# Compiler Error CS9036 + +Required member 'memberName' must be assigned a value, it cannot use a nested member or collection initializer. + +When initializing an object with a `required` member, you must directly assign the member a value. You cannot use a nested member or collection initializer to set properties of the `required` member without first instantiating it. + +## Example + +The following sample generates CS9036: + +```csharp +class C +{ + public string? Prop { get; set; } +} + +class Program +{ + public required C C { get; set; } + + static void Main() + { + var program = new Program() + { + // error CS9036: Required member 'Program.C' must be assigned a value, it cannot use a nested member or collection initializer. + C = { Prop = "a" } + }; + } +} +``` + +## Solution + +To fix this error, directly assign a new instance of the required property and initialize its members: + +```csharp +class C +{ + public string? Prop { get; set; } +} + +class Program +{ + public required C C { get; set; } + + static void Main() + { + var program = new Program() + { + // Correct: Assign a new instance of C and then initialize its Prop property + C = new C { Prop = "a" } + }; + } +} +``` + +For more information on required members, see the [required modifier](../keywords/required.md) reference article and [Object and Collection Initializers](../../programming-guide/classes-and-structs/object-and-collection-initializers.md) guide. diff --git a/docs/csharp/language-reference/toc.yml b/docs/csharp/language-reference/toc.yml index a04a064bdd8a9..cd4c02b0fef02 100644 --- a/docs/csharp/language-reference/toc.yml +++ b/docs/csharp/language-reference/toc.yml @@ -1984,6 +1984,8 @@ items: href: ./compiler-messages/cs8812.md - name: CS8515 href: ./compiler-messages/cs8515.md + - name: CS9036 + href: ./compiler-messages/cs9036.md - name: CS9043 href: ./compiler-messages/cs9043.md - name: Level 1 warning messages diff --git a/docs/csharp/misc/sorry-we-don-t-have-specifics-on-this-csharp-error.md b/docs/csharp/misc/sorry-we-don-t-have-specifics-on-this-csharp-error.md index 54771c4384058..d656365bf31d5 100644 --- a/docs/csharp/misc/sorry-we-don-t-have-specifics-on-this-csharp-error.md +++ b/docs/csharp/misc/sorry-we-don-t-have-specifics-on-this-csharp-error.md @@ -550,7 +550,6 @@ f1_keywords: - "CS9033" - "CS9034" - "CS9035" - - "CS9036" - "CS9037" - "CS9038" - "CS9039"