I have a large static list which is basically a lookup table, so I initialise the table in code.
private class MyClass
{
private class LookupItem
{
public int Param1 { get; set; }
public int Param2 { get; set; }
public float Param2 { get; set; }
public float Param4 { get; set; }
}
private static List<LookupItem> _lookupTable = new List<LookupItem>()
{
new LookupItem() { Param1 = 1, Param2 = 2, Param3 = 3 Param4 = 4 },
new LookupItem() { Param1 = 5, Param2 = 6, Param3 = 7 Param4 = 8 },
//etc
}
}
The real LookupItem
has many more properties, so I added a constructor to allow for a more compact initialisation format:
private class MyClass
{
private class LookupItem
{
public int Param1 { get; set; }
public int Param2 { get; set; }
public float Param2 { get; set; }
public float Param4 { get; set; }
public LookupItem(int param1, int param2, float param3, float param4)
{
Param1 = param1;
Param2 = param2;
Param3 = param3;
Param4 = param4;
}
}
private static List<LookupItem> _lookupTable = new List<LookupItem>()
{
new LookupItem(1, 2, 3, 4),
new LookupItem(5, 6, 7, 8),
//etc
}
}
What I'd really like to do is use the collection initialiser format for the object itself so I can get rid of the new LookupItem()
on every line. eg:
private static List<LookupItem> _lookupTable = new List<LookupItem>()
{
{ 1, 2, 3, 4 },
{ 5, 6, 7, 8 },
//etc
}
Is this possible? I like to think it is because the KeyValuePair
's of a Dictionary<>
can be initialised in this way.
MSDN States:
Collection initializers let you specify one or more element intializers when you initialize a collection class that implements IEnumerable. The element initializers can be a simple value, an expression or an object initializer. By using a collection initializer you do not have to specify multiple calls to the Add method of the class in your source code; the compiler adds the calls.
Does this mean I need to implement IEnumerable
on my LookupItem
class and return each parameter? My class isn't a collection class though.
You should never do this in a real program
- okay. What should you do in a real program? Scenario: porting from Java, and have a class that has 3Add()
overloads and implementsIEnumerable<T>
. If I implementICollection<T>
I will have a bunch ofRemove()
,Clear()
methods that I don't want or need. Is there another solution to make it more clear how to use the collection initializers using Intellisense, or is writing documentation my only option? – Cognoscenti