Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Object Initializer for object collections

Tags:

c#

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}
 };
like image 568
rick schott Avatar asked Oct 08 '09 17:10

rick schott


People also ask

What is object initializer?

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.

What is collection initializer?

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.

How do you initialize an object in C sharp?

You can use object initializers to initialize type objects in a declarative manner without explicitly invoking a constructor for the type.


1 Answers

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},
        };
    }
like image 141
nitzmahone Avatar answered Oct 30 '22 05:10

nitzmahone