There's a syntax in C# that I discovered recently that enables you to initialize a read-only collection during initialization:
class Foo
{
public List<Bar> Bars { get; } = new List<Bar>();
}
var foo = new Foo
{
Bars =
{
new Bar()
}
}
Which is great as it leads to very expressive code. But I have a situation where I already have a collection of Bar, and I want to initialize it using this syntax (even though Bars is readonly). Is there a way to do this?
var bar = new List<Bar>();
var foo = new Foo
{
Bars = bar // error: Property or indexer Foo.Bar cannot be assigned to -- it is read only
}
Foo, you can simply add a constructor that takesList<Bar>as an argument -var foo = new Foo(bar);Fooconstructor to takeBaras a parameter and change to thispublic List<Bar> Bars = { get; private set; }private set;is useful in c#5, but in c#6 you can have read-only properties by only specifying{get;}.private setwill work from outside theFoo?