0

I am new to c# as am a php / js / html developer. I have 8 switches named relay_1,relay_2,relay_3 etc etc I need to be able to change the state of these but I would like to do through a for loop so the number is dynamic. I have tried various methods but to no avail. Any help would be greatly appreciated. This is what I would like ( not correct )

for (int i = 0; i < 8; i++)
{
  relay_" + i.IsChecked = true;
}
2
  • 5
    You don't want to do this, you want to learn about collection types. Trust me, every beginner thinks they want this, but it's only because they don't understand collections (arrays, lists, etc.) Commented Jan 4, 2014 at 1:54
  • 2
    forget php, js and html. C# is a strongly typed (serious) language. You need to learn about OOP and as mentioned above you're looking for a List or Collection. Commented Jan 4, 2014 at 2:03

1 Answer 1

5

You cannot generate the name of a variable dynamically, but you can create an array of relay objects (the allRelays variable below), and do your operation in a loop, like this:

var allRelays = new {relay_0, relay_1, relay_2, relay_3, relay_4, relay_5, relay_6, relay_7, relay_8};
foreach (var relay in allRelays) {
    relay.IsChecked = true;
}
Sign up to request clarification or add additional context in comments.

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.