user3246761
user3246761

Reputation: 3

Creating a universal boolean in C#

I write:

bool example = true under the code for say, a button event: private void button1_Click(object sender, EventArgs e)

I am trying to change the value of this bool when the user pushes a button.

The problem is, my bool is only recognized in this context. When I try to use it under private void checkBox1_CheckedChanged(object sender, EventArgs e) Visual Studio notifies me of an error saying the name doesn't exist in the context.

Where should I be putting the code for a bool?

Thanks.

Upvotes: 0

Views: 159

Answers (4)

clcto
clcto

Reputation: 9648

As a member of the class;

public class MyClass
{
    private bool example = false;
    private void button1_Click(object sender, EventArgs e)
    {
        example = true;
    }

    private void checkBox1_CheckedChanged(object sender, EventArgs e)
    {
        //example available
    }
}

Upvotes: 1

Juan Rada
Juan Rada

Reputation: 3766

Use static variable or class level.

Upvotes: 0

Selman Genç
Selman Genç

Reputation: 101681

Where should I be putting the code for a bool?

Outside of your methods, in the class level

public class MyForm : Form
{
   // here is class level

   public void SomeMethod()
   {
      // here is method level
   }
}

Upvotes: 1

Simon Whitehead
Simon Whitehead

Reputation: 65079

Move it to class-level: that is, a member of the Form class:

public class YourForm : Form {
    private bool _example = true;

    // ... your event handlers here

    private void checkBox1_CheckedChanged(object sender, EventArgs e) {
        _example = false; // etc
    }
}

Upvotes: 3

Related Questions