- Home /
Is it bad to use "this" keyword for variables, methods etc. from base class?
class A
{
public int a;
}
class B : A
{
public B()
{
this.a = 5;
}
}
Is this bad practice when we can use the keyword "base" ? If it is give me a thorough explanation why is it bad apart from the fact that the person reading our code might think at first that this variable is from the very class he sees it being used in(I'm not saying that this isn't enough just if there are other reasons)
Answer by Baste · Jan 21, 2015 at 09:42 AM
So, base exists to fix the problem where you have overridden a method, but need to call the method from the base class. So it's either used when you only want to override a method in some cases:
public override void MyMethod() {
if(SomeCheck())
DoMyOwnThing();
else
base.MyMethod();
}
Or if you want to add extra behaviour:
public override void MyMethod() {
base.MyMethod();
ExtraStuff();
}
In your example, base is really not necessary. Neither is using this. If your variable is named well, you usually know where it's from due to the context. And unless you're writing code in a plain text editor, you'll have a go-to-declaration shortcut if you're wondering where a variable is declared.
My general rule is to only use this and base if they actually change the behavior of the program. So base.something only if "something" has been overridden in this class, but you want to reference "something" in the superclass. The same thing with this; only use it if there's a variable in the local scope with the same name:
public class HerpDerp {
private Foo foo;
public void BoringExample(Foo foo, int bar) {
foo.intVal = bar;
this.foo.intVal = bar;
}
}
Now, using base and this in other contexts are not necessarily wrong; I can see the argument to always prefacing fields with 'this' to make it easier for the reader to see that you're referencing a field rather than a variable. I tend to see that desire as a symptom of writing too long methods where it's not easy to see where a variable's from. In the end, it comes down to preference.
Answer by DaDonik · Jan 21, 2015 at 08:41 AM
It makes absolutely no difference for the computer, all it does is to enhance the readability for the user. I would use it!
Edit: Well i should have read the question correctly...
IMO it completely fine to use the this keyword in an inner class. If the programmer doesn't know which class he is in....get another programmer asap!