Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In C#, is "this" keyword required? [duplicate]

Tags:

c#

In the following constructor, is the 'this' keyword required? I know I can remove it, it complies and everything is okay. If I omit 'this' will that cause problems for me down the road? Is ommission of 'this' considered bad practice?

    // Constructor:
    public Employee(string name, string alias)
    {
        // Use this to qualify the fields, name and alias:
        this.name = name;
        this.alias = alias;
    }
like image 819
DenaliHardtail Avatar asked Oct 05 '09 01:10

DenaliHardtail


People also ask

What does << mean in C?

<< is the left shift operator. It is shifting the number 1 to the left 0 bits, which is equivalent to the number 1 .

What does %d do in C?

%d is a format specifier, used in C Language. Now a format specifier is indicated by a % (percentage symbol) before the letter describing it. In simple words, a format specifier tells us the type of data to store and print. Now, %d represents the signed decimal integer.


1 Answers

No, this is purely optional in almost all cases. The only reason it is required in your example is to disambiguate between local variables and parameters and member variables that happened to have the same identifier name.

You could avoid the use of this by renaming either the parameter or the field to something unique.

like image 139
Andrew Hare Avatar answered Oct 02 '22 20:10

Andrew Hare