views:

49

answers:

3

Hi. 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 ??

  }
}
A: 

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

main()
{
  private MyClass object;

  private void button1_click { 

  object = new MyClass();
aJ
Basically the answer, so I don't want to duplicate, but you may want to elaborate...?
David M
+4  A: 

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();
  }
}
PoweRoy
This correct - but keep in mind that if you're initializing your new MyClass in one of the methods, then you're going to have to check that it has been initialized in other methods that use it prior to doing so.You may actually be better off initializing your MyClass object in the constructor that you can be assured that it is always non-null. (Assuming that this is possible.) You could also consider making a property for it, and lazy-loading when it is used.
Andrew Anderson
+1  A: 

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)

Andreas Niedermair
+1 for actually using correct syntax and not trying to declare a variable called 'object'...
mdresser
:) you could, but it should rather state `@object`
Andreas Niedermair