I have a project which stores values in SQL and later retrieves them for analysis. To keep track of what kinds of values might be stored, I created a class roughly like this:
private class DataField
{
public string FieldName;
public string FieldType;
}
When values are being read for analysis, a switch statement is used as follows (simplified):
switch (DataField.FieldType)
{
case "int":
List<int> InputData = new List<int>();
// Populate list from DB
break;
case "bool":
List<bool> InputData = new List<bool>();
// Populate list from DB
break;
}
Rather than maintain code in multiple places, I am looking for a way to get rid of the switch statement, but that means I need to dynamically create collections based on the type. Current that type is (naively?) a string, but I think I could improve this by changing the class:
private class ImprovedDataField
{
public string FieldName;
public Type FieldType;
}
And then dynamically create collections somehow:
Type DataType = typeof(DataField.FieldType);
List<DataType> InputData = new List<DataType>();
// Populate list from DB
This of course does not work, resulting in a Type or namespace name expected
error.
Unfortunately I'm not very familiar with working with the Type
class, nor generics nor anonymous types as I search for a solution (nothing seems to be appropriate).
How can I reduce duplication of code where the only difference in each switch statement branch is the type of variable collection being produced?