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 };
Object Collection Initilizer:
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}
};
An object initializer is an expression that describes the initialization of an Object . Objects consist of properties, which are used to describe an object. The values of object properties can either contain primitive data types or other objects.
C# 3.0 (. NET 3.5) introduced Object Initializer Syntax, a new way to initialize an object of a class or collection. Object initializers allow you to assign values to the fields or properties at the time of creating an object without invoking a constructor.
You can use object initializers to initialize type objects in a declarative manner without explicitly invoking a constructor for the type.
If you look at the docs for collection initializers, it's all about the collection's Add method. Just subclass the closed generic List over your type and make an Add method with the naked parameters. Like
public class MyColl : List<ChildObject>
{
public void Add(string s1, int a1, int a2)
{
base.Add(new ChildObject(s1, a1, a2));
}
}
public class ChildObject
{
public ChildObject(string s1, int a1, int a2)
{
//...
}
}
Then calling it looks like:
static void Main(string[] args)
{
MyColl x = new MyColl
{
{"boo", 2, 4},
{"mang", 3, 5},
};
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With