Initialize variable in declaration or constructor?

U

User N

In cases where a variable can be initialized in the declaration or
constructor, which approach do you take? Are there any genuine
advantages to one approach over the other?


Example:

public class foo
{
private int maxItems = 5;
private ArrayList items = new ArrayList();

public foo()
{
}
}

vs

public class foo
{
private int maxItems;
private ArrayList items;

public foo()
{
maxItems = 5;
items = new ArrayList();
}
}
 
B

Bruce Wood

I always initialize in the constructor for the converse of the reason
that you mentioned: because some variables can't be initialized in the
declaration, and I prefer to always go to one place to see what my
initial values are.

By initializing in the constructor (and in only one constructor), I
have everything in one place and always in the same place.
 
J

Jon Skeet [C# MVP]

User N said:
In cases where a variable can be initialized in the declaration or
constructor, which approach do you take? Are there any genuine
advantages to one approach over the other?

I tend to initialise in the declaration, as for default values that
means there's only one place I need to look even if there are several
constructors which can't logically call each other. It also means when
I go to see the documentation for a variable I see its default initial
value too.

It's not something I'd get hung up over either way though - it's not a
religious thing with me, unlike, say, bracing style :)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top