Groups | Blog | Home
all groups > c# > june 2005 >

c# : Initialize variable in declaration or constructor?


Bruce Wood
6/2/2005 8:36:40 PM
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.
User N
6/2/2005 10:25:43 PM
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();
}
}
Jon Skeet [C# MVP]
6/3/2005 7:01:53 AM
[quoted text, click to view]

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 :)

--
Jon Skeet - <skeet@pobox.com>
http://www.pobox.com/~skeet
AddThis Social Bookmark Button