I've got a situation where I have a business object with about 15 properties of different types. The business object also has to implement an interface which has the following method:
object GetFieldValue(string FieldName);
I can see 2 ways of implementing this method:
Use a switch statement:
switch ( FieldName )
{
case "Field1": return this.Field1;
case "Field2": return this.Field2;
// etc.
}
Use a dictionary (SortedDictionary or HashTable?):
return this.AllFields[FieldName];
Which would be more efficient?
Added: Forgot to say. This method is for displaying the item in a grid. The grid will have a column for each of these properties. There will routinely be grids with a bit over 1000 items in them. That's why I'm concerned about performance.
Added 2:
Here's an idea: a hybrid approach. Make a static dictionary with keys being property names and values being indices in array. The dictionary is filled only once, at the startup of the application. Every object instance has an array. So, the lookup would be like:
return this.ValueArray[StaticDictionary[FieldName]];
The dictionary filling algorithm can use reflection. The properties itself will then be implemented accordingly:
public bool Field1
{
get
{
object o = this.ValueArray[StaticDictionary["Field1"]];
return o == null ? false : (bool)o;
}
set
{
this.ValueArray[StaticDictionary["Field1"]] = value;
}
}
Can anyone see any problems with this?
It can also be taken one step further and the ValueArray/StaticDictionary can be placed in a separate generic type ValueCollection<T>
, where T
would specify the type for reflection. ValueCollection will also handle the case when no value has been set yet. Properties could then be written simply as:
public bool Field1
{
get
{
return (bool)this.Values["Field1"];
}
set
{
this.Values["Field1"] = value;
}
}
And in the end, I'm starting to wonder again, if a simple switch statement might not be both faster and easier to maintain....