Skip to content
Discussion options

You must be logged in to vote

Shouldn't it work in this case, too?

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.

Replies: 2 comments 42 replies

Comment options

You must be logged in to vote
20 replies
@fandrei
Comment options

@CyrusNajmabadi
Comment options

@jnm2
Comment options

jnm2 Dec 14, 2024
Collaborator

@fandrei
Comment options

@CyrusNajmabadi
Comment options

Answer selected by CyrusNajmabadi
Comment options

You must be logged in to vote
22 replies
@CyrusNajmabadi
Comment options

@CyrusNajmabadi
Comment options

@fandrei
Comment options

@CyrusNajmabadi
Comment options

@CyrusNajmabadi
Comment options

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
4 participants