In the following code:
public class A
{
public A():this(null){}
public A(string b){/*code here*/}
}
What is the use of first constructor?
In the following code:
public class A
{
public A():this(null){}
public A(string b){/*code here*/}
}
What is the use of first constructor?
Having a parameterless default constructor is required when object initialization is used:
Employee e = new Employee() {FirstName="John", LastName="Smith"};
In this case, I probably would not use constructor chaining, though. Constructor overloading gives you an alternative way to initialize with parameters. Where constructor chaining is really useful is in making constructor parameters optional; C# doesn't support optional parameters (yet).
"Best practice" will depend on the situation, usage, architecture, requirements, etc. (ISO Consulting Rule Number One: "It depends.")
When you have a constructor with a parameter
public A(string b){ /* code here */ }
public A():this("") { } //default
the default constructor actually calls the "parameter constructor" with "" as a parameter. You are passing a parameter. This is done in order to avoid writing the same code twice
It's a constructor overload.
I agree it doesn't seem to be very useful in this case because most likely the uninitialised value for a string is null anyway.
See also Constructors in C#
this happens when you're overloading constructors.
in your example the empty contructor public A():this(null){}
looks for a constructor that can take in an object value of null. since a string is an object that can take nulls, it calls that constructor.
this example seems very simplistic.
a more meaningful example (but still keeping it basic):
public class AddNumbers
{
public AddNumbers():this(100, 100)
{ }
public AddNumbers(int x, int y)
{
int sum = x + y;
Console.WriteLine(sum.ToString());
}
}
in this example, when a calling program calls the empty constructor, it will output 200. because it is calling the AddNumbers method with x = 100, y = 100.
i know it's a simple example but i hope that makes it clearer.
The first constructor is passing
null
into parameter b of the second constructor.Thus if you call
new A()
it will be the same as callingnew A(null)