Assigning to dynamic variable?

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
 
N

Nicholas Paldino [.NET/C# MVP]

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.
 
B

Brett Romero

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top