Collection initializers in custom classes

suggest change

To make a class support collection initializers, it must implement IEnumerable interface and have at least one Add method. Since C# 6, any collection implementing IEnumerable can be extended with custom Add methods using extension methods.

class Program
{
    static void Main()
    {
        var col = new MyCollection {
            "foo",
            { "bar", 3 },
            "baz",
            123.45d,
        };
    }
}

class MyCollection : IEnumerable
{
    private IList list = new ArrayList();

    public void Add(string item)
    {
        list.Add(item)
    }

    public void Add(string item, int count)
    {
        for(int i=0;i< count;i++) {
            list.Add(item);
        }
    }

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

static class MyCollectionExtensions
{
    public static void Add(this MyCollection @this, double value) => 
        @this.Add(value.ToString());
}

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:


Collection Initializers:
* Collection initializers in custom classes

Table Of Contents
17 Regex
19 Arrays
21 Enum
22 Tuples
24 GUID
26 Collection Initializers
27 Looping
36 Casting
46 Methods
88 Events
92 Structs
104 Indexer
106 Stream
107 Timers
109 Threading
127 Caching
135 Pointers
147 C# Script