Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a New Class with Collection Initializers in C# [duplicate]

I have a class that I created. I would like to allow the class to be able to have a collection initializer. Here is an example of the class:


public class Cat
{
    private Dictionary catNameAndType = new Dictionary();

    public Cat()
    {

    }

    public void Add(string catName, string catType)
    {
        catNameAndType.Add(catName,catType);
    }

}

I would like to be able to do something like this with the class:


Cat cat = new Cat()
{
    {"Paul","Black"},
    {"Simon,"Red"}
}

Is this possible to do with classes that are not Dictionaries and Lists?

like image 634
user489041 Avatar asked Dec 10 '22 05:12

user489041


1 Answers

In addition to an Add method, the class must also implement the IEnumerable interface.

See also: Object and Collection Initializers (C# Programming Guide)

like image 82
dtb Avatar answered May 17 '23 23:05

dtb