4

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?

0

3 Answers 3

12

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

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

Sign up to request clarification or add additional context in comments.

Comments

1

Yes, it is possible. Actually, you almost solved it yourself. The requirements to use a collection initializer like that, is an Add method that takes two methods (which you have), and that the type implements IEnumerable (which you are missing). So to get your code to work; use something like:

public class Cat : IEnumerable<KeyValuePair<string,string>>
{
    private Dictionary<string,string> catNameAndType = new Dictionary<string,string>();

    public Cat()
    {

    }

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

    public IEnumerator<KeyValuePair<string,string>> GetEnumerator() 
    {
        return catNameAndType.GetEnumerator();
    }

    IEnumerator IEnumerable.GetEnumerator() 
    {
        return GetEnumerator();
    }
}

1 Comment

Doh... Looks like we were both writing ours at same time...
1

Yep, as stated in other answers (just to give more detail), just implement IEnumerable<T> and have some Add() method(s):

// inherit from IEnumerable<whatever>
public class Cat : IEnumerable<KeyValuePair<string,string>>
{
    private Dictionary<string, string> catNameAndType = new Dictionary<string, string>();

    public Cat()
    {

    }

    // have your Add() method(s)
    public void Add(string catName, string catType)
    {
        catNameAndType.Add(catName, catType);
    }

    // generally just return an enumerator to your collection
    public IEnumerator<KeyValuePair<string, string>> GetEnumerator()
    {
        return catNameAndType.GetEnumerator();
    }

    // the non-generic form just calls the generic form
    IEnumerator IEnumerable.GetEnumerator()
    {
        return GetEnumerator();
    }
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.