Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 797
Stécy Avatar asked Sep 22 '09 17:09

Stécy


2 Answers

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.

like image 57
Adam Lear Avatar answered Sep 25 '22 08:09

Adam Lear


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

like image 37
Joel Day Avatar answered Sep 23 '22 08:09

Joel Day