0

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

  }
}

3 Answers 3

4

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();
  }
}
Sign up to request clarification or add additional context in comments.

1 Comment

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.
1

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)

2 Comments

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

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

main()
{
  private MyClass object;

  private void button1_click { 

  object = new MyClass();

1 Comment

Basically the answer, so I don't want to duplicate, but you may want to elaborate...?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.