Home > Back-end >  How to change the value of a boolean array that is called by a for loop parameter in c#
How to change the value of a boolean array that is called by a for loop parameter in c#

Time:08-11

I have the following problem:

Inside a for loop, I try to call an array that is from another class and I have it as public, through the parameter, when I want to assign a value to the parameter, it is not reflected in the array.

1). Is it the correct way to call the array using the parameter?

2). Where am I failing and why is the value "True" that I assign to the matrix not assigned?

static public void VentanaReserva(System.Windows.Forms.Button button , bool Valor1  )
        {
            if (Valor1 == false)
            {
                button.BackColor = System.Drawing.Color.Red;
                Valor1 = true;     **//This is where you assign the value of true** -----

                MessageBoxBase messageBoxBase = new MessageBoxBase();

                messageBoxBase.ShowDialog();
                ValorCancha.SumaDeCanchaPequeña();

            }

 private void button1_Click(object sender, EventArgs e)//this is the place where I assign the parameters that are in another class
        {

            EstadoDeReserva.VentanaReserva(button1, ValorCancha.Visualizar[0,1]);
         }

CodePudding user response:

I assume you want to do something like this:

var myBools = new bool[10];
for(var i = 0; i < myBools.Length; i  ){
    MyMethod(myBools[i]);
}
void MyMethod(bool myBool){
    myBool = !myBool;
}

This will not work since primitive types like bools are passed by value. So assigning a new value to any parameter will not affect the original value.

The easiest way to get around this is to just return the new value and assign it:

var myBools = new bool[10];
for(var i = 0; i < myBools.Length; i  ){
    myBools[i] = MyMethod(myBools[i]);
}
bool MyMethod(bool myBool){
    return !myBool;
}

There is also the possibility to pass parameters by reference, as well as ref return and ref local, but that is not something I would recommend unless you have some very specific use cases. Methods tend to be easiest to use if they take some parameters, return some value(s), and does not have any side effects.

  • Related