0

Is there any practical difference between those two ways of instantiating an object?

public class myClass
{
   private myType myObject = new myType();

}

and

public class myClass
{
   private myType myObject;

   public myClass()
   {
       myObject = new myType();
   }

}

Thanks for helping.

Eric Andres
  • 3,417
  • 2
  • 24
  • 40
Richard77
  • 20,343
  • 46
  • 150
  • 252

3 Answers3

0

No there isn't any practical difference, between the two ways you provided. They are exaclty the same.

Christos
  • 53,228
  • 8
  • 76
  • 108
0

The answer is yes

When you read the code later, you will look in the constructor to see what happens when you create the class. If you put constructor logic outside the constructor another developer may miss what's going on. So put your constructor logic in your constructor. It makes a difference.

Niels Brinch
  • 3,033
  • 9
  • 48
  • 75
  • You are talking about readability, OP is asking about differences in object instansiation – Yuval Itzchakov Jun 09 '14 at 21:30
  • 1
    Moreover, I would imagine that if you asked 100 programmers which style they prefer, you would get a pretty even split. It definitely isn't black and white. – BradleyDotNET Jun 09 '14 at 21:32
0

As far as the code goes, there isn't much difference. Initialization in the declaration happens in document order, top to bottom, which might or might not have side effects. From a practical perspective, if you do any interactive debugging at all, you'll grow to hate declaration initializations, unless you enjoy stepping through them one at a time.

Keep your code tidy and initialize things in the constructors.

Nicholas Carey
  • 71,308
  • 16
  • 93
  • 135