0

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?

4
  • 3
    You can do this with Reflection, but it's non-trivial. What are you trying to accomplish? Commented Nov 5, 2010 at 23:45
  • WPF? Win Forms? ASP.NET? Commented Nov 5, 2010 at 23:46
  • 2
    Another programmer coming from PHP would be my guess ;-) Commented Nov 5, 2010 at 23:47
  • @Jim, reflection is not needed, and this IS trivial. (in at least WinForms, WPF, and ASP.NET) Commented Nov 5, 2010 at 23:55

3 Answers 3

3

You don't need reflection, you can use

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

Sign up to request clarification or add additional context in comments.

1 Comment

I stand corrected. My non-GUI focus is showing. Nice answer.
2

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?

1 Comment

Actually I don't really need this. :P I'm just curious if this is possible as I couldn't find anything about it. I'm not interested in other soulutions for making a function that I wrote as example, only if it is possible to simply combine a variable and object's name, but I guess it's not unfortunately. :)
1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.