You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
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
+
classC
22
+
{
23
+
publicstring? Prop { get; set; }
24
+
}
25
+
26
+
classProgram
27
+
{
28
+
publicrequiredCC { get; set; }
29
+
30
+
staticvoidMain()
31
+
{
32
+
varprogram=newProgram()
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
+
classC
47
+
{
48
+
publicstring? Prop { get; set; }
49
+
}
50
+
51
+
classProgram
52
+
{
53
+
publicrequiredCC { get; set; }
54
+
55
+
staticvoidMain()
56
+
{
57
+
varprogram=newProgram()
58
+
{
59
+
// Correct: Assign a new instance of C and then initialize its Prop property
60
+
C=newC { 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.
0 commit comments