1

Which is recommended for initialization of class fields in C#:

class Foo
{
    public X x = new X(); // or any default value...
    public Foo(X _x)
    {
       x = _x;
    }
}

Or

class Foo
{
    public X x;
    public Foo(X _x)
    {
       x = _x;
    }
}

Please note in the second version, it is probable that I introduce other constructors where x may not be initialized!

  • what language is this? – gnat Mar 27 '15 at 10:23
  • 1
    @gnat I edited it to point the language – Ahmad Mar 27 '15 at 10:29
  • In the C# coding standards where I work there is a note saying that direct initializations of a field may cause the debugger to skip around while debugging the instantiation of a class. This might be something to consider. (I've not tested this myself.) – paul Mar 27 '15 at 20:31
5

You should choose between init in declaration or constructor, not both.

In a language that has a default constructor where you don't have to explicitly provide a constructor if the default is all you need, a declaration init may be fine. As soon as you need an explicit constructor with parameter, I tend to move everything to constructor(s), to ensure that init behaviour is in one place.

Too be honest, I hardly ever use declaration init, but that may just be preference. My perceived advantage is that all init behaviour is always encapsulated in constructors: I never have to look in two places (or miss it up in the variable declaration).

Re:

"it is probable that I introduce other constructors where x may not be initialized"

You should always code constructors to re-use another constructor as appropriate. E.g. in your example, adding another constructor with additional param could be done like this:

class Foo
{
    public X x;
    public Y y;

    public Foo(X _x)
    {
       x = _x ?? new X();
    }

    //WRONG!
    public Foo(X _x, Y _y)
    {
       x = _x;
       y = _y;
    }

    //Right
    public Foo(X _x, Y _y)
    {
       this(_x);
       y = _y ?? new Y();
    }
}

Finally, when delegating to another constructor, always prefer this() to base() (super() in Java) since it adds to local cohesion. For more detail on this() vs base() in C#, see e.g. https://stackoverflow.com/questions/3797528/base-and-this-constructors-best-practices

  • +1. IMHO it boils down to if you care that the field is null after Foo is instantiated. public X x - this guy is public AND we have a constructor that <strike>does</strike> did not check for null. This tells me we don't care. Caveat emptor! – radarbob Mar 27 '15 at 20:36

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.