mmssaann
mmssaann

Reputation: 1507

Do we need this keyword in .net 4.0 or 4.5

I am currently reviewing code written in c#, visual studio 2012.

In lot of places, the code is written using this key word, for ex:

this.pnlPhoneBasicDtls.Visible = true;
this.SetPhAggStats(oStats);

There are many other places where the controls of the page are referred using this key word.

Can somebody advise do we really need to use this here? Any consequences of removing this keyword?

Thanks in advance..

Upvotes: 0

Views: 111

Answers (3)

Matthew Strawbridge
Matthew Strawbridge

Reputation: 20630

The this keyword is usually optional.

It's sometimes used to disambiguate fields from arguments if the same name is being used for both, for example:

void Main()
{
    var sc = new SomeClass();
    sc.SomeMethod(123);
    Console.WriteLine(sc.thing);
}

public class SomeClass
{
    public int thing;

    public void SomeMethod(int thing)
    {
        this.thing = thing + 1;
    }
}

In the example above it does make a difference. Inside SomeMethod, this.thing refers to the field and thing refers to the argument.

(Note that the simpler assignment thing = thing is picked up as a compiler error, since it is a no-op.)

Of course, if you use ReSharper then any unnecessary this. (together with unused using statements, unreachable code, etc.) will be greyed out and you can remove them very quickly. The same is probably true of similar tools like CodeRush.

Upvotes: 0

Aravind
Aravind

Reputation: 1549

Its Optional you can use the

Property directly like   pnlPhoneBasicDtls.Visible = true;

Upvotes: 2

Michael Stum
Michael Stum

Reputation: 181004

No, "this" is optional. It's usually included in code generated by a tool and by people who feel the need to be explicit or who want to differentiate it from an argument to the method.

Upvotes: 4

Related Questions