To refer to instance variables, should I use the "this" keyword...
class Foo
{
private int bar;
public Foo(int bar)
{
this.bar = bar;
}
}
OR the "m_" prefix (Hungarian naming convention where m means "member variable")...
class Foo
{
private int m_bar;
public Foo(int bar)
{
m_bar = bar;
}
}
Are there any situations where one provides an advantage over the other?
In answer to "Are there any cases where you should always use this ?" You should use it when it is needed to avoid ambiguity, for example if there is another variable with the same name in scope.
'm' means the variable is a member variable of the class... Save this answer.
Method names should always begin with a lower case character, and should not contain underscores.
A variable's name can be any legal identifier — an unlimited-length sequence of Unicode letters and digits, beginning with a letter, the dollar sign " $ ", or the underscore character " _ ". The convention, however, is to always begin your variable names with a letter, not " $ " or " _ ".
this
is standard, more readable, and less error prone.
It will help you when you are mistakenly shadowing variables or and trying to access non-static field in static code.
i.e to avoid this
int m_bar;
public Foo(int m_bar)
{
m_bar = m_bar;
}
and static int m_bar;
int m_bar;
public Foo(int bar)
{
this.bar = m_bar; // a warning static field being accessed as non-static
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With