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 ??
}
}
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 ??
}
}
make object
as member variable of the class where functions are defined.
main()
{
private MyClass object;
private void button1_click {
object = new MyClass();
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();
}
}
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)