Initialize variable in declaration or constructor?

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • User N

    Initialize variable in declaration or constructor?

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

  • Bruce Wood

    #2
    Re: Initialize variable in declaration or constructor?

    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.

    Comment

    • Jon Skeet [C# MVP]

      #3
      Re: Initialize variable in declaration or constructor?

      User N <UserN@invalid. invalid> wrote:[color=blue]
      > 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?[/color]

      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.co m>
      Pobox has been discontinued as a separate service, and all existing customers moved to the Fastmail platform.

      If replying to the group, please do not mail me too

      Comment

      Working...