Answer the question
In order to leave comments, you need to log in
What is the best way to instantiate a class?
What is the best way to instantiate a class?
1 way:
class A {}
class B
{
A instance;
public void SomeMethod()
{
instance = new A();
}
}
class A {}
class B
{
public void SomeMethod()
{
A instance = new A();
}
}
Answer the question
In order to leave comments, you need to log in
The first way creates a class field, the second way creates a local variable. If other methods need a previously created instance, or when this method is called again, the same instance is needed, then make a field. If you need a new instance every time you call a method, make it a local variable. Remember that after the method ends, all local variable data is deleted (unless you return an instance via method return).
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question