Assigning to dynamic variable?

  • Thread starter Thread starter Brett Romero
  • Start date Start date
B

Brett Romero

I have methods such as the following:

void GetA20(somevar)
{
A20 = ONE
}

void GetA30(somevar)
{
A30 = ONE
}

void GetA40(somevar)
{
A40 = ONE
}

I need the three (A20, A30, A40) variables since they are used in XML,
per the receiver's guidelines. I like to create one method, send in
another variable containing the string 20, 30, or 40 and assign to A.
For example:

timeRange = 20;

void GetA(somevar, timeRange)
{
(A + timeRange) = ONE
}

which would mean:
A20 = ONE

The above is an extremely simple scenario. I can use case or if
conditionals but would rather avoid them. Is there a clean way to do
this?

Thanks,
Brett
 
Brett,

Assuming you have fields named A20, A30 and so on, you could use
reflection to get the field and then set the value.

You could also just use a dictionary which is keyed on the string values
"A20", "A30" and so on to store your values.

Hope this helps.
 
Thanks Nicholas. In the end, I did go with the Dictionary<>. I
thought about using a ref out parameter but it didn't seem as flexible.

Brett
 
Back
Top