Collection expressions vs readonly #8889
-
The following code works: class Test
{
public readonly List<int> List = [];
}
static readonly Test Obj = new()
{
List = { 0 },
}; and this code works too: static readonly List<int> Vals = [0]; However, this code doesn't compile: static readonly Test Obj1 = new()
{
List = [0],
}; Shouldn't it work in this case, too? |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 42 replies
-
No. The list is readonly, so it cannot be assigned. To your examples: static readonly Test Obj = new()
{
List = { 0 },
}; This is not an assignment of hte list. This is translated to: Test __test = new Test();
__test.List.Add(0);
Obj = __test; This is fine as the list is not assigned to, it just has a value added to it. static readonly List<int> Vals = [0]; This is the initializer of a readonly field, which is always legal. A readonly field can always be initialized with an iniitalizer, or by an assignment in the constructor of the type owning the readonly field. |
Beta Was this translation helpful? Give feedback.
-
Note: this is unrelated to collection expression. The following are illegal as well: static readonly Test Obj1 = new()
{
List = new(),
};
static readonly Test Obj1 = new()
{
List = new List<int>(),
};
static readonly Test Obj1 = new()
{
List = null,
};
static readonly Test Obj1 = new()
{
List = someOtherList,
}; All of these are illegal, not because a collection expr was used, but because the field is readonly. You cannot assign it outside of hte field-initializer/constructor. |
Beta Was this translation helpful? Give feedback.
No. The list is readonly, so it cannot be assigned.
To your examples:
This is not an assignment of hte list. This is translated to:
This is fine as the list is not assigned to, it just has a value added to it.
This is the initializer of a readonly field, which is always legal. A readonly field can always be initialized with an iniitalizer, or by an assignment in the constructor of the type owning the readonly field.