user3159236
user3159236

Reputation: 1

Access dynamic object by name in a loop

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;
}

Upvotes: 0

Views: 110

Answers (1)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726987

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;
}

Upvotes: 5

Related Questions