Please consider following example:
public class UnitTest
{
[Fact]
public void TestList()
{
var sample = new SampleList
{
Fields = { "b", "c" }
};
var count = sample.Fields.Count;
Assert.Equal(2, count);
}
[Fact]
public void TestArray()
{
var sample = new SampleArray
{
Fields = { "b", "c" }
};
var count = sample.Fields.Count;
Assert.Equal(2, count);
}
}
public class SampleList
{
public ICollection<string> Fields { get; set; } = new List<string>
{
"a"
};
}
public class SampleArray
{
public ICollection<string> Fields { get; set; } = new string[]
{
"a"
};
}
The syntax that you've used works only in object initializer and it tries to add specified items to collection.
In the TestList() test case assert fails because it adds "b", "c" to
the list and results in "a", "b", "c"
In the TestArray() test case assert fails because it throws following
exception
System.NotSupportedException: 'Collection was of a fixed size.'
It means that if you want to use this object initialization syntax you have to use collections that don't have fixed size.