Search code examples
c#constructorchaining

In C#, what is the best/accepted way of doing constructor chaining?


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?


Solution

  • 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.