简体   繁体   中英

What is C# code doing:

In the following code:

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

What is the use of first constructor?

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)

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.

这是一个默认构造函数,使用b == null调用秒。

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

This method comes in handy in those times.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM