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.

4
  • 8
    It is the exact same code. Easy to see with a disassembler like ildasm.exe Commented Jun 9, 2014 at 21:22
  • 1
    It is the same until you add another Constructor. Commented Jun 9, 2014 at 21:23
  • 1
    Introduce a base class (actually, there already is one... Object). Initializing your fields inside or outside the constructor changes the order in which they are initialized. Commented Jun 9, 2014 at 21:30
  • For more on my prior comment, see this answer (that links over to Eric Lippert's blog) Commented Jun 9, 2014 at 21:32

3 Answers 3

0

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

Sign up to request clarification or add additional context in comments.

Comments

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.

2 Comments

You are talking about readability, OP is asking about differences in object instansiation
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.
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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.