Using this () in code

I am new to CSharp. I saw "this ()" in some code. My question is: suppose if I call

Paremeterized constructor, can I use the constructor without using paremeterless ?. But in accordance with the design of the constructor, I believe that the gapless constructor will be executed first. Can you explain this with a simple example so that I can find out exactly when I should call it () "Thanks in advance.

 public OrderHeader() { }

 public OrderHeader(string Number, DateTime OrderDate, int ItemQty)
            : this()
        {

          // Initialization goes here ....
        }
+5
source share
4 answers

( ) : base(), - . : this() .. - . , : (...) : base (...) .

: this() , . : (...) , - - :

public Foo() : this(27, "abc") {} // default values
public Foo(int x, string y) {...validation, assignment, etc...}
+6

, this(), , .

, , Id, full Name, this, :

public Foo()
{
    Id = ComputeId();
}

public Foo(string name)
    : this()
{
    Name = name;
}

, paramterfull Id, this():

public Foo()
{
    Id = ComputeId();
}

public Foo(int id)
{
    Id = id;
}

, :

public Foo(int id, string name)
    : this(id)
{
    Name = name;
}
+6

Parameterless - , . - , this().

, this().

class Test
{
    public int x;
    public int y;

    public Test()
    {
        x = 1;
    }

    public Test(int y) : this() // remove this() and x will stay 0
    {
        this.y = y;
    }


class Program
{
    static void Main(string[] args)
    {
        var t = new Test(5);
        Console.WriteLine("x={0} y={1}", t.x, t.y);
    }
}

As mentioned in another answer - the rule for calling the constructor without parameters is first applied to the keyword base(). If you do not specify which base constructor will be called, then the compiler will try to call the parameter without parameters.

+1
source

Constructor chain!

The important part to remember is the order in which the chain is called.

public OrderHeader() { //Executed First
    _number = "";
    _orderDate = DateTime.Now();
}

public OrderHeader(string Number)
            : this()
        {
          _number = Number;
        }

public OrderHeader(string Number, DateTime OrderDate, int ItemQty)
            : this(Number)
        {

           _orderDate = OrderDate;
           _itemQty = ItemQty;
        }
0
source

All Articles