Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to initialize an object from one method to another method within a class?

Tags:

methods

c#

class

In a class, I have 2 methods. In method1 I created an object, but I can't use the same object in method2.

Why? Please help with a simple example.

The coding is too big, so I have given the layout

public class Sub
{
}

public class DataLoader
{
    public void process1()
    {
        Sub obj = new Sub();
    }

    public void process2()
    {
        // here I can't use the object
    }
}
like image 816
Praveen Avatar asked Feb 13 '26 23:02

Praveen


2 Answers

The reason why this isn't working is scope. A local variable can only be accessed from the block it is declared in. To access it from multiple methods, add a field or pass it to the other method as a parameter.

Field:

class YourClass
{
    object yourObject;

    void Method1()
    {
        yourObject = new object();
    }

    void Method2()
    {
        int x = yourObject.GetHashCode();
    }
}

Parameter:

class YourClass
{
    void Method1()
    {
        Method2(new object());
    }

    void Method2(object theObject)
    {
        int x = theObject.GetHashCode();
    }
}
like image 182
Adam Avatar answered Feb 15 '26 12:02

Adam


You should use member variables in your class.

public class DataLoader
{
    private Sub mySub;

    public void Process1()
    {
        mySub = new Sub();
    }

    public void Process2()
    {
        if(mySub == null) 
            throw new InvalidOperationException("Called Process2 before Process1!");            

        // use mySub here
    }
}

Read up on different variable scopes (specifically, instance variables in this case). You can also pass your object as a parameter, like codesparkle mentioned in their answer.

like image 31
Adam Lear Avatar answered Feb 15 '26 11:02

Adam Lear



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!