Consider the following class with a read-only (or getter-only) property ClientPermissions :
internal class Client
{
public string? ClientId { get; set; }
public HashSet<string> ClientPermissions { get; } = new(StringComparer.Ordinal);
public HashSet<string> ClientTokens { get; set; } = new(StringComparer.Ordinal);
}
It seems I can't assign an object during construction to the read-only auto-property ClientPermissions while I can assign it values with an anonymous collection initializer
SO 5646285 gives a hint that for the object initializer the dotnet compiler actually compiles this into using object creation and then addition of the values.
Ok.. but why can I use an anonymous collection initializer than with this read-only auto-property?
// Works - no complaints from compiler when I use collection initializer on read-only auto-property ClientPermissions
var sc1 = new Client() { ClientId = "c1", ClientPermissions = { "a1", "b1" }, ClientTokens = { "t1", "t2" } };
// Works - no complaints from compiler when I use collection initializer on read-only auto-property and object initializer on normal/full auto-property
var sc2 = new Client() { ClientId = "c2", ClientPermissions = { "a1", "b1" }, ClientTokens = new HashSet<string>{ "t1", "t2" } };
// DOES NOT COMPILE - Compiler complains with a CS0200: Property or indexer '...' cannot be assigned to -- it is readonly
// auto-initialize syntax
var sc3 = new Client() { ClientId = "c3", ClientPermissions = new HashSet<string> { "a1", "b1" }, ClientTokens = new HashSet<string> { "t1", "t2" } };