In C# you can initialise a collection property as such:
public class MyClass
{
public string Name { get; set ;}
}
public class MyContainerClass
{
public ICollection<MyClass> Collection { get; set; }
}
var myObject = new MyContainerClass
{
Collection = new List<MyClass>
{
new()
{
Name = "1",
},
new()
{
Name = "2",
},
},
}
For a class with a pre-instantiated, readonly collection you can do something similar:
public class MyReadonlyContainerClass
{
public ICollection<MyClass> Collection { get; } = new List<MyClass>();
}
var myObject = new MyReadonlyContainerClass
{
Collection = {
new()
{
Name = "1",
},
new()
{
Name = "2",
},
},
};
What I would like to know if is there is any way to use initialisation to add the members of an existing collection to a readonly collection class. For example, it might look like:
var myCollection = Enumerable.Range(1,10).Select(i => new MyClass{ Name = i.ToString() });
var myObject = new MyReadonlyContainerClass{ Collection = { myCollection } };
The above does not compile as the Add
method of List<T>
takes a single T
instance rather than an IEnumerable<T>
but I was wondering if there is a syntactically correct way to do this. Something like the spread operator in javascript maybe?
Update for context
I think from the comments below I should have been clearer about why I would like a solution to this. I am using EF Core Power Tools to generate C# classes from an existing DB schema. The EF 7 version has removed the setter from the autogenerated navigation properties (explained here). We have a test suite which will be time consuming to refactor that has instances of initialising navigation properties in the way I explained above. If a refactor is necessary then so be it, I was just looking for a language feature I may have overlooked.