开发者

bool variable not getting set to true C#

开发者 https://www.devze.com 2023-04-12 06:11 出处:网络
I have a boolean which is set to false when being declared, public bool row1 = false; However, when I run some code in order to set the boolean to true, it doesn\'t seem to be wokring,

I have a boolean which is set to false when being declared,

public bool row1 = false;

However, when I run some code in order to set the boolean to true, it doesn't seem to be wokring,

if (currentBox.BackColor == cardColour)
{
    MessageBox.Show("Please Draw a Card.");
}
else if (currentBox.BackColor != cardColour)
{
    row = true;
}

The above开发者_JAVA百科 code is the method body of a method which is being called in a picturebox mouse click event method (using row1 in the parameters when calling the method). At its current state, it's saying it's false when it should be set to true.

Here is the code which is calling the method.

private void rowOne_MouseClick(object sender, MouseEventArgs e)
{
    AllowTake(row1, currentCardPictureBox, Color.White, sender, e);
}

Thanks for any help.


You should pass the row parameter by ref: row1 is a separate local variable and its value is not used outside the method.

void MakeTrue(bool flag) {
    flag = true;
}

//Calling code:
bool myFlag = false;
MakeTrue(myFlag);

After MakeTrue is called the value of myFlag doesn't change. Its value is used to initialize a flag argument in MakeTrue method and that's it. After that whatever you do to flag won't affect the value of myFlag.

Now, if you do this:

void MakeTrue(ref bool flag) {
    flag = true;
}

//Calling code:
bool myFlag = false;
MakeTrue(ref myFlag);

you will get the desired (in your case) behavior: flag will be just an alias for myFlag variable and whatever you assign to it will become the value of myFlag.

Some links to read:

  • Passing parameters (MSDN)
  • Parameters passing in C#
  • Why ref and out in C#.
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号