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.
To use a collection initializer, your class has to:
IEnumerable
Add
methodsFor 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...");
}
}
See more on this question at Stackoverflow