Tvde1 Tvde1 - 10 months ago 35
C# Question

Editing booleans from another class in an array

This might be a nooby question, but I'm stuck.

What I have here is code in my form. This is the event I have assigned to my buttons.

These buttons are supposed to switch states of


Those booleans are all
public static bool boolA

Here is my form's code.

public void switchButton(object sender, EventArgs e)
Button[] buttons = { btnA, btnB };
bool[] bools = { SomeClass.boolA, SomeClass.boolB };

Button button = (Button)sender;
int index = Array.IndexOf(buttons, button);

if (bools[index])
bools[index] = false;
button.Text = "Start";
bools[index] = true;
button.Text = "Stop";

What happens is, the button's text gets set to "Stop" but never to "Start" when I click it again.

Help would very much be appriciated.

Answer Source

A bool is a value type. They are atomic in .Net. So when you assign them to a new variable they are copied. So in:

bool[] bools = { SomeClass.boolA, SomeClass.boolB };

bools[0] lives in one memory address and SomeClass.boolA lives in a different one. There is no relation (unlike a reference type). Or to put it another way bools[0] != SomeClass.boolA. Changing bools[0] does not affect SomeClass.boolA and vice versa.

You can see this by running this code:

bool a = false;
bool[] bools = new bool[] {a};
bools[0] = true;

a == false; //true
bools[0] == true; //true

So you can't do what you want how you want to do it. Basically your going to have to manipulate the SomeClass.boolA, etc. independantly, probably using a switch or an if.