Initialize my class with array syntax
Do I need to initialize my class as an array or a dictionary like
private class A
{
private List<int> _evenList;
private List<int> _oddList;
...
}
and tell
A a = new A {1, 4, 67, 2, 4, 7, 56};
and in my constructor fill in _ evenList and _ oddList with your values.
+3
Alexander Leyva Caro
source
to share
2 answers
To use a collection initializer , your class must:
- Implement
IEnumerable
- Implement appropriate methods
Add
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...");
}
}
+6
Jon Skeet
The only way I can think of is to pass the 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 ...
}
}
Using:
A foo = new A({1, 4, 67, 2, 4, 7, 56});
0
Paul stoner