Click here to Skip to main content
15,507,266 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
private void button1_Click(object sender, EventArgs e)
        {
            Cat kitty = new Cat();
        }

        private void button2_Click(object sender, EventArgs e)
        {
           //kitty.eat();
        }


how to access kitty.eat() by button2?
now kitty is not exit in the current context.


thank you.

What I have tried:

private Cat button1_Click(object sender, EventArgs e)


or done by EventArgs ?
Posted
Updated 7-Nov-17 20:51pm

Declare the Cat variable outside the event and make it common across the page

Cat kitty;  // declare outside
       private void button1_Click(object sender, EventArgs e)
       {
           kitty = new Cat();
       }

       private void button2_Click(object sender, EventArgs e)
       {
           if (kitty != null)  // validate for null value.
               kitty.eat();
       }
 
Share this answer
 
Comments
BillWoodruff 8-Nov-17 6:32am    
+5 meow !
Karthik_Mahalingam 8-Nov-17 6:34am    
Thank you Bill :)
When you write code like that, you can't. Your code declares kitty as a local variable - which means it is created on the stack and assigned a new cat instance from the heap. When the button1_Click event handler method exits, the variable is automatically destroyed, and there are no more references to the heap based object: kitty goes out of scope at the end of the method.
Since the scope of any variable is limited to the curly brackets that enclose it (With the exception of class level variables with the appropriate attributes: public, protected, etc.) they cannot be accessed outside that curly bracket block:
C#
{
   int a = 1;
   if (a == 1)
      {
      int b = 2;
      } // b goes out of scope here
   a = b; // Illegal: b is not in scope and is not available
} // a goes out of scope here

To "share" the variable between the two handlers, move the definition outside any method:
C#
private Cat kitty = null;
private void button1_Click(object sender, EventArgs e)
    {
    kitty = new Cat();
    }

private void button2_Click(object sender, EventArgs e)
    {
    kitty.eat();
    }
 
Share this answer
 
Comments
BillWoodruff 8-Nov-17 6:32am    
+5 purrrrrrr

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900