Creating a new class with collection initializers in C #

I have a class that I created. I would like to allow the class to have a collection initializer. Here is an example 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 do something like this with a class:

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

Can this be done with classes that are not dictionaries and lists?

+4
source share
3 answers

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

See also: Initializers for Objects and Collections (C # Programming Guide)

+12
source

Yes it is possible. Actually, you almost decided it yourself. The requirements for using the collection initializer are similar to this Add method, which uses two methods (which you have) and that the type implements IEnumerable (which you do not see). So that your code works; 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
source

Yep, as pointed out in other answers (just for details), just implement IEnumerable<T> and use several Add() methods:

 // 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(); } } 
+1
source

All Articles