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
}
}
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();
}
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With