Praveen
Praveen

Reputation: 56501

How to initialize an object from one method to another method within a 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
    }
}

Upvotes: 2

Views: 5090

Answers (4)

Dave M
Dave M

Reputation: 1322

The short answer (without seeing your code) is that the object created in Method1 doesn't have any visibility, or scope, in Method2.

There are already some good answers here that show you how to solve your specific problem. But the real answer here is to familiarize yourself generally with the concept of Scope. It's a fundamental part of programming and learning more about it will help you tons.

There are many good articles and videos on the subject. This video is a great start. Good luck!

Upvotes: 1

Adam Lear
Adam Lear

Reputation: 38758

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.

Upvotes: 2

Adam
Adam

Reputation: 15805

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();
    }
}

Upvotes: 7

Paul
Paul

Reputation: 21975

You have to set the object as a class field, then you can access it from every method of your class.

Upvotes: 0

Related Questions