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?
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.
I prefer the first. The behavior of the constructors will always be coherent and predictable that way, plus it reduces code duplication.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With