Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using 'this' keyword in constructor

Tags:

c#

What is the difference b/w the following two codes. What is the use of using 'this' keyword in the constructor.

Ex 1:

public Product(string name){
this.Name = name;
}

Ex 2:

public Product(string name){
Name = name;
}

I know this refers to the calling object. Just I couldn't able to get the difference?

can some one please explain?

like image 748
Bhaskar Avatar asked Dec 09 '25 22:12

Bhaskar


2 Answers

Example 1 uses an explicit reference to this. This is not really needed as there's no ambiguity in this case. If the parameter was called Name instead, the explicit this would be required to resolve the ambiguity.

like image 71
Brian Rasmussen Avatar answered Dec 12 '25 11:12

Brian Rasmussen


It is absolutely optional in the example you provide.

Mainly, it implicitely tells the user that the member that is worked with is part of the current class object.

One practice was to differentiate parameters from members or fields like the following:

public class Customer {
    private string name;

    public Customer(string name) {
        this.name = name;
    } 
}

For readability's sake, one would put this in front of the name field to make it clear that the value of the name parameter is assigned to the this class' name field.

In such situation, it is necessery, as both the constructor parameter and the field have the same name. Otherwise, if they were different variable names, the this keyword would be optional.

like image 22
Will Marcouiller Avatar answered Dec 12 '25 11:12

Will Marcouiller



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!