Skip to content

Commit bb59f4a

Browse files
CopilotBillWagner
andcommitted
Move CS9036 to compiler-messages folder and update TOC
Co-authored-by: BillWagner <[email protected]>
1 parent cea7032 commit bb59f4a

File tree

2 files changed

+68
-0
lines changed

2 files changed

+68
-0
lines changed
Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
1+
---
2+
description: "Compiler Error CS9036"
3+
title: "Compiler Error CS9036"
4+
ms.date: 05/19/2023
5+
f1_keywords:
6+
- "CS9036"
7+
helpviewer_keywords:
8+
- "CS9036"
9+
---
10+
# Compiler Error CS9036
11+
12+
Required member 'memberName' must be assigned a value, it cannot use a nested member or collection initializer.
13+
14+
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.
15+
16+
## Example
17+
18+
The following sample generates CS9036:
19+
20+
```csharp
21+
class C
22+
{
23+
public string? Prop { get; set; }
24+
}
25+
26+
class Program
27+
{
28+
public required C C { get; set; }
29+
30+
static void Main()
31+
{
32+
var program = new Program()
33+
{
34+
// error CS9036: Required member 'Program.C' must be assigned a value, it cannot use a nested member or collection initializer.
35+
C = { Prop = "a" }
36+
};
37+
}
38+
}
39+
```
40+
41+
## Solution
42+
43+
To fix this error, directly assign a new instance of the required property and initialize its members:
44+
45+
```csharp
46+
class C
47+
{
48+
public string? Prop { get; set; }
49+
}
50+
51+
class Program
52+
{
53+
public required C C { get; set; }
54+
55+
static void Main()
56+
{
57+
var program = new Program()
58+
{
59+
// Correct: Assign a new instance of C and then initialize its Prop property
60+
C = new C { Prop = "a" }
61+
};
62+
}
63+
}
64+
```
65+
66+
For more information on required members, see the [required modifier](../language-reference/keywords/required.md) reference article and [Object and Collection Initializers](../programming-guide/classes-and-structs/object-and-collection-initializers.md) guide.

docs/csharp/language-reference/toc.yml

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1984,6 +1984,8 @@ items:
19841984
href: ./compiler-messages/cs8812.md
19851985
- name: CS8515
19861986
href: ./compiler-messages/cs8515.md
1987+
- name: CS9036
1988+
href: ./compiler-messages/cs9036.md
19871989
- name: CS9043
19881990
href: ./compiler-messages/cs9043.md
19891991
- name: Level 1 warning messages

0 commit comments

Comments
 (0)