Pros and Cons of using this keyword in c#
In programming you can use the this keyword
this.Textbox
or just
Textbox
What is the best practice?
Some benefits I can see is that using this makes it easier to see in intellisense and makes it easier to understand that it is a property.
Currently I don't use this... I read in some article somewhere that the guy removed all the references, but I don't remem开发者_JAVA百科ber why.
What are the pros and cons of using the this keyword?
Using this
systematically will mean that you don't fall into a trap of referring to a local variable when in fact you want a member of this
.
The downside: using this
will make your code more verbose.
It's really up to personal preference.
The only cons are that it is more typing. Using this
(esp. consistently) also precludes, for example, using a parameter when you meant to use a property, e.g. a method f(Textbox textbox) => {textbox = textbox}
when you meant to say this.Textbox = textbox.
Using it consistently not only makes it impossible to do so but also makes it stand out when you possibly could have.
It's a matter of preference, really. Sometimes you have to use the this
keyword, in cases like this:
private string Foo;
public void Bar(string Foo)
{
this.Foo = Foo;
}
Not having the this
will result in a bug where the parameter just sets itself to itself. It's less verbose, but some may say it's also less clear (hence preference).
I prefer leaving out this.
because it's less typing and less clutter and only use it when necessary because the identifier would be ambiguous otherwise.
As a sidenote I like the way member acces is handled in Cobra. It requires them to be prefixed with a .
(or _
for privates). So you'd use .member=parameter
. And the first is obviously a member and the second a local variable. An elegant way to remove the ambiguity without becoming verbose.
I've just started to remove this. qualification from a codebase which has turned up a consequence:
Extension methods must have a this. prefix!
Thus, use of extension methods isn't transparent unless this. qualification is used generally.
精彩评论