I’m reading in data from an xml file and have the following switch statement
switch (localVariable)
{
case "myStringVariable":
myClass.myStringVariable= subReader.ReadElementContentAsString();
break;
case "myOtherStringVariable":
myClass.myOtherStringVariable= subReader.ReadElementContentAsString();
break;
case "myBoolVariable":
myClass.myBoolVariable= subReader.ReadElementContentAsBool();
break;
I would like to optimize this into something like
switch (localVariable)
{
case "myStringVariable":
case "myOtherStringVariable":
myClass.localVariable= subReader.ReadElementContentAsString();
break;
case "myBoolVariable":
myClass.localVariable= subReader.ReadElementContentAsBool();
break;
You could use reflection to take it a step further:
Add the following method to your class:
Then, rather than using a switch statement in your code, you just call: