Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using this() in code

Tags:

c#

I am new to CSharp.I have seen "this()" in some code.My question is Suppose if i call

Paremeterized constructor ,am i invoking the paremeterless constructor forcefully?.But According to constructor construction ,i believe parameterless constructor will be executed first.Can you please explain this with simple example so that i can get exactly when should i call "this()".Thanks in advance.

 public OrderHeader() { }

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

          // Initialization goes here ....
        }
like image 436
user1233805 Avatar asked Feb 26 '12 12:02

user1233805


3 Answers

By default (for classes), there is an implicit :base(), so it is always chaining something. Adding :this() calls the parameterless constructor of the current type, and so on - sooner or later it will call down to a base constructor of some kind. Yes, the :this(...) or :base(...) happens before the constructor body.

In the example shown, adding :this() does no harm, but does nothing useful either. In more complex scenarios, :this(...) is commonly used to avoid duplicating constructor code - usually directing all constructors to the most parameterized version - for example:

public Foo() : this(27, "abc") {} // default values
public Foo(int x, string y) {...validation, assignment, etc...}
like image 170
Marc Gravell Avatar answered Oct 18 '22 01:10

Marc Gravell


Well, you should use this() if you want to call the parameterless constructor, it's as simple as that.

For example, if you have two constructors, where the parameterless initializes Id and the parameterfull also initializes Name, you should use this, so that you don't repeat yourself:

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

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

On the other hand, if the paramterfull constructor is a different way to initialize the Id, you don't have to call this():

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

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

This syntax is also not limited to the parameterless constructor, you can call any other constructor the same way:

public Foo(int id, string name)
    : this(id)
{
    Name = name;
}
like image 26
svick Avatar answered Oct 18 '22 01:10

svick


Parameterless constructor will not be executed first by default - compiler will use only the constructor you're invoking explicitly. If you need to invoke the parameterless constructor for some reason then use this().

You can see the difference in the example below if you remove 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 was mentioned in another answer - the rule to invoke the parameterless constructor first applies to the base() keyword. If you don't provide which base constructor to invoke then the compiler will attempt to invoke the parameterless one.

like image 41
AlexD Avatar answered Oct 17 '22 23:10

AlexD