Chiri Vulpes
Chiri Vulpes

Reputation: 488

How do I write an array-style initialiser for a class I wrote?

In C# you can initialise arrays and other objects, such as Lists, or even Dictionaries, like this:

Type[] array = new Type[] { new Type(), new Type(), new Type()...};

or, more bizarre looking, for Dictionaries:

Dictionary<string, object> dictionary = new Dictionary<string, object> () {
    { "key1", value },
    { "key2", value }
};

How would I write a constructor for my own type of object? In my case, I want to use it for an object I named LayerGroup:

LayerGroup layers = new LayerGroup() {
    "background",
    "foreground",
    "menu",
    "entities"
};

And I'd like to know how to do it in Dictionary style too:

LayerGroup layers = new LayerGroup() {
    { 4, "background" },
    { 1, "foreground" },
    { 0, "menu" },
    { 3, "entities" }
};

(In that case, I would of course have a different structure for the LayerGroup class, that's just an example)

Upvotes: 2

Views: 86

Answers (2)

Dima
Dima

Reputation: 6741

To get collection initializer you'll need to implement 2 methods and inherit your class from IEnumerable:

public class LayerGroup: IEnumerable
{
    private readonly IList<string> _collection = new List<string>();

    public void Add(string value)
    {
        _collection.Add(value);
    }

    public IEnumerator GetEnumerator()
    {
        return _collection.GetEnumerator();
    }
}

Similarly, if you want to get "Dictionary like" initialization, you need to implement

public void Add(string key, string value)
{
  ...
}

or whole IDictionary interface, if you want to get full spectrum of Dictionary functionality.

Upvotes: 5

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 727137

The array-style initializers are called Collection Initializers. In order for collection initializers to work, the object being initialized needs to implement IEnumerable, and provide the corresponding Add method, with the signature matching the parameters that you plan to supply.

Hence the LayerGroup class needs to contain an Add method that looks like this:

public void Add(string name);

This would let you initialize LayerGroup with a list-like initializer. If you provide an Add method like this

public void Add(int number, string name);

you would be able to use a dictionary-like initializer (i.e. the last snippet from your question).

Upvotes: 3

Related Questions