N
N
newProgrammer2016-03-06 21:52:27
C++ / C#
newProgrammer, 2016-03-06 21:52:27

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

2 way:
class A {}

class B
{
   public void SomeMethod()
      {
         A instance = new A();
      }
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexey Pavlov, 2016-03-06
@newProgrammer

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 question

Ask a Question

731 491 924 answers to any question