1

I want to create a custom class that can be initialized like arrays can,

var myCollection = new MyCollection<string> {"a", "b", "c"}

Is there a syntax for creating a class that can interpret that?

I know how to do a similar thing with class properties, such as

var person = new Person { Name = "Santi", LastName = "Arizti" };

But that is not what I am looking for.

This question might already exist, but I just don't know the name of this feature to effectively search it online.

2
  • 1
    Check this article: mariusschulz.com/blog/… Commented Mar 13, 2020 at 23:33
  • If your class is a collection, wouldn't you get this functionality from implementing IEnumerable or IList? Commented Mar 13, 2020 at 23:36

2 Answers 2

4

Your class must

  1. Implement IEnumerable
  2. Have an Add method

That's it.

public class MyCollection<T> : IEnumerable<T>
{
    protected readonly List<T> _list = new List<T>();

    public void Add(T item) 
    {
        _list.Add(item);
    }

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

    public IEnumerator<T> GetEnumerator()
    {
        return _list.GetEnumerator();
    }
}

public class Program
{
    public static void Main()
    {
        var x = new MyCollection<string>
        {
            "A","B"
        };
    }
}

Here is a Link to Fiddle

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

Comments

3

Constructing an object using {...} simply creates it using the default constructor and calls an Add method present on it for each of the arguments (or tuples of arguments if nested {...} is used). It only has to implement IEnumerable.

Your example is essentially equivalent to:

var myCollection = new MyCollection<string>();
myCollection.Add("a");
myCollection.Add("b");
myCollection.Add("c");

Here's the simplest example of such a class that can be "initialized" with anything:

public class TestClass : IEnumerable
{
    public void Add<T>(params T[] args)
    {

    }

    IEnumerator IEnumerable.GetEnumerator()
    {
        throw new NotImplementedException();
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.