nixon
nixon

Reputation: 1

using object in multiple function

How can i use object from one function in another ?

main()
{
  private void button1_click { 

  MyClass object = new MyClass();
  object.blabla();

  }

  private void button2_click {

  // how can i use object from button1_click ??

  }
}

Upvotes: 0

Views: 100

Answers (3)

RvdK
RvdK

Reputation: 19800

By storing the object out of the scope of a function.

main()
{
  MyClass obj;

  private void button1_click 
  { 
    obj = new MyClass();
    obj.blabla();
  }

  private void button2_click 
  {
    //maybe check for null etc
    obj.dosomethingelse();
  }
}

Upvotes: 4

aJ.
aJ.

Reputation: 35480

make object as member variable of the class where functions are defined.

main()
{
  private MyClass object;

  private void button1_click { 

  object = new MyClass();

Upvotes: 0

user57508
user57508

Reputation:

basically this is a more fundamental question, which can be solved as eg

class program
{
    void Main(string[] args)
    {
      private MyClass FooInstance;
      private void button1_click()
      {
        // TODO be defensive: check if this.FooInstance is assigned before, to not override it!
        this.FooInstance = new MyClass();
        this.FooInstance.blablabla();
      }

      private void button2_click()
      {
        // TODO add some null check aka make sure, that button1_click() happened before and this.FooInstance is assigned
        this.FooInstance = ....;
      }
    }
}

you may also choose lazy-loading as an option (mentioned by Andrew Anderson)

Upvotes: 1

Related Questions