views:

264

answers:

7

Given the following class:

public class MyClass
{
    private string _param;

    public MyClass ()
    {
        _param = string.Empty;
    }

    public MyClass (string param)
    {
        _param = param;
    }
}

I am torn apart between two ways to chain those constructors:

The first one:

public MyClass () : this (string.Empty)
{
}

public MyClass (string param)
{
    _param = param;
}

The second one:

public MyClass ()
{
    _param = string.Empty;
}

public MyClass (string param) : this ()
{
    _param = param;
}

So, is it better to chain from the parameterless constructor or the other way around?

+11  A: 

With your example, I'd go the first way. The second doesn't actually eliminate any code duplication that you are presumably trying to avoid, since you still have to explicitly set _param. The empty this() call in the second approach is completely gratuitous.

Anna Lear
Indeed, and it seems to be the consensus here.
Stecy
+4  A: 

I prefer the first. The behavior of the constructors will always be coherent and predictable that way, plus it reduces code duplication.

Joel Day
+3  A: 

Chain from pramater less to pramater,

so calling from lessor param constructors with default vals to more parameters

public MyClass()
{
    MyClass(default value here);
}

public Myclass(value)
{
    _value = value;
}
astander
+1  A: 

I'd imagine that it's always better to chain from lesser to greater, i.e. why assign an empty string then a given string in the constructor when it makes more sense to pass the default (string.Empty) to the parameterised constructor.

Lazarus
A: 

If you state your goal here as "providing a default when no value is specified", then you should clearly use the first approach.

The general rule would then be: chain from least-specific constructor to most-specific.

Bryan Watts
+1  A: 

I prefer the first as well. Just as in a complex derived class inheriting from a simple base class, you want the "complex" constructor to build on the functionality of the "basic" one.

Jason Williams
+1  A: 

Second example in your case really does not make sense, since you duplicate assignment of the class member (if you use MyClass (string param) constructor).

Second approach is more useful if chained constructors are "adding functionality".

Example:

public MyClass ()
{
    _param0 = string.Empty;
}

public MyClass (string param1) : this ()
{
    _param1 = param1;
}

public MyClass (string param1, string param2) : this (param1)
{
    _param2 = param2;
}

In your particular case, the first example is obviously much more appropriate, since you have only one assignment to the same member.

Peter Stegnar