Alexander Leyva Caro
Alexander Leyva Caro

Reputation: 1253

Initialize my class with array syntax

Is there anyway to initialize my class like an array or a dictionary, for example

    private class A
    {
        private List<int> _evenList;
        private List<int> _oddList;
        ...
    }

and say

A a = new A {1, 4, 67, 2, 4, 7, 56};

and in my constructor fill _evenList and _oddList with its values.

Upvotes: 3

Views: 90

Answers (2)

Paul Stoner
Paul Stoner

Reputation: 1512

The only way that I can think of would be to pass your array through the constructor

private class A
{
    private List<int> _evenList;
    private List<int> _oddList;

    public A (int[] input)
    {
        ... put code here to load lists ...
    }
}

Usage:

A foo = new A({1, 4, 67, 2, 4, 7, 56});

Upvotes: 0

Jon Skeet
Jon Skeet

Reputation: 1499730

To use a collection initializer, your class has to:

  • Implement IEnumerable
  • Implement appropriate Add methods

For example:

class A : IEnumerable
{
    private List<int> _evenList = new List<int>();
    private List<int> _oddList = new List<int>();

    public void Add(int value)
    {
        List<int> list = (value & 1) == 0 ? _evenList : _oddList;
        list.Add(value);
    }

    // Explicit interface implementation to discourage calling it.
    // Alternatively, actually implement it (and IEnumerable<int>)
    // in some fashion.
    IEnumerator IEnumerable.GetEnumerator()
    {
        throw new NotImplementedException("Not really enumerable...");
    }
}

Upvotes: 6

Related Questions