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.
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".
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