Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can you use array-like constructor for a class

Tags:

c#

constructor

Is it possible to have class constructor to behave like array initializer, e.g. Foo foo = { 1, 2, 3 };

With implicit casting I get pretty close: Foo foo = new int[] { 1, 2, 3 };

But I'd love to add a bit more syntactic sugar as this bit will be used throughout my code. Making it a bit more JSON-like.

like image 610
aXu_AP Avatar asked Nov 03 '25 09:11

aXu_AP


1 Answers

You can get fairly close if your class implements IEnumerable<T> and Add(T) where T is the type of the items in your collection.

For example, given this:

public sealed class Foo: IEnumerable<int>
{
    public void Add(int item)
    {
        _items.Add(item);
    }

    public IEnumerator<int> GetEnumerator()
    {
        return _items.GetEnumerator();
    }

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

    readonly List<int> _items = new List<int>();
}

You can do this:

Foo foo = new Foo {1, 2, 3};

Unfortunately, the following syntax is reserved for arrays only:

Foo foo = {1, 2, 3}; // Won't compile. You need the "new Foo".
like image 198
Matthew Watson Avatar answered Nov 05 '25 00:11

Matthew Watson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!