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?
In addition to an Add
method, the class must also implement the IEnumerable
interface.
See also: Object and Collection Initializers (C# Programming Guide)
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