I am wanting to find out if there is a way to initialize a List<T> where T is an object much like a simple collection gets initialized?
Simple Collection Initializer:
List<int> digits = new List<int> { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
List<ChildObject> childObjects = new List<ChildObject>
{
new ChildObject(){ Name = "Sylvester", Age=8 },
new ChildObject(){ Name = "Whiskers", Age=2 },
new ChildObject(){ Name = "Sasha", Age=14 }
};
The question is, how and if you can do something like this?
List<ChildObject> childObjects = new List<ChildObject>
{
{ "Sylvester", 8} , {"Whiskers", 2}, {"Sasha", 14}
};
You can’t do this without creating your own class derived from
List<ChildObject>as per Lee’s answer. It’s unfortunate that extension methods aren’t considered for collection initalizers, otherwise this would work: