If you have the class:
class Foo {
Bar Bar { get; } = new Bar();
}
class Bar {
string Prop {get; set; }
}
You can use a object initialise like:
var foo = new Foo {
Bar = { Prop = "Hello World!" }
}
If you have a class
class Foo2 {
ICollection<Bar> Bars { get; } = new List<Bar>();
}
You can write
var foo = new Foo2 {
Bars = {
new Bar { Prop = "Hello" },
new Bar { Prop = "World" }
}
}
but, I would like to write something like
var items = new [] {"Hello", "World"};
var foo = new Foo2 {
Bars = { items.Select(s => new Bar { Prop = s }) }
}
However, the code above does not compile with:
cannot assigne IEnumerable to Bar
I cannot write:
var foo = new Foo2 {
Bars = items.Select(s => new Bar { Prop = s })
}
Property Bars is readonly.
Can this be archived?
If you read the actual compiler errors (and the docs for collection initializers), you'll find that collection initializers are merly syntactic sugar for
Add()
calls:So the syntax
SomeCollection = { someItem }
will be compiled toSomeCollection.Add(someItem)
. And you can't addIEnumerable<Bar>
to a collection ofBar
s.You need to manually add all items:
Or, given shorter code is your goal, do the same in
Foo2
's constructor:Then you can initialize Foo2 like this:
For a funny abuse of the collection initializer syntax as supposed by @JeroenMostert, you could use an extension method:
Which allows this:
But that's just nasty.