What is C# code doing:

449 views Asked by At

In the following code:

public class A
{
public A():this(null){}
public A(string b){/*code here*/}
}

What is the use of first constructor?

7

There are 7 answers

1
Geoff On BEST ANSWER

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 calling new A(null)

0
Neil N On

Some interfaces or designers require there to be a "parameterless" constructor.

This method comes in handy in those times.

0
Cylon Cat On

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.")

0
Svetlozar Angelov On

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

1
SMART_n On

It's a default constructor that calls second with b==null.

1
rohancragg On

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#

0
Kamal On

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.