Ethesen
Ethesen

Reputation: 3

How to add a variable into object's name in C#?

Let's say I want a function like this:

private void ShowLabel(byte Variable)
{
labelXXX.Show();
}

But with Variable's value instead of XXX. Is it possible?

Upvotes: 0

Views: 1716

Answers (3)

Ben Voigt
Ben Voigt

Reputation: 283883

You don't need reflection, you can use

But using a Dictionary<byte, Label>, as suggested by CodeInChaos, would be preferable.

Upvotes: 3

CodesInChaos
CodesInChaos

Reputation: 108880

While you can do it with reflection, it smells. If you have many labels which are only distinguished by a number, perhaps create them at runtime and put them in List or dictionary, so you can look them up from the ID.

You could iterate over all the children of the parent control, compare their name to the name you want to find the control you want. But that has a bad smell.

Upvotes: 1

Bryan
Bryan

Reputation: 2791

you could create an array of the Labels and use the value of Variable as the index to that array. But you question is pretty vague. Could you give more info on why you need to do this?

Upvotes: 2

Related Questions