3

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.

1
  • select the even values for the evenList and the odd values for the oddList Commented Nov 7, 2014 at 13:07

2 Answers 2

6

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...");
    }
}
Sign up to request clarification or add additional context in comments.

9 Comments

are you sure that i can use this: new A {1, 4, 67, 2, 4, 7, 56}; with that
@AlexanderLeyvaCaro: Are you sure that you can't? (Hint: try it.)
And if i was use the dictionaty syntax, how is it?
@AlexanderLeyvaCaro: What do you mean by "dictionary syntax"?
like this: new A {{1,3,5},{2,4,6}}
|
0

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});

1 Comment

@JonSkeet, It is true, one does learn something new everyday, if one keeps their mind open. I withdraw my answer as Jon's appears to far superior.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.