I name private member variables _x
to avoid such cases1. Arguments for/against this abound.
private string _name;
public Employee(string name, string alias)
{
// Equivalent to `this._name = name`, as _name is not shadowed
_name = name;
}
On the other hand, I am opposed to naming parameters _x
because parameter names are part of the public contract2. This contract should be clean, stable, and should not be dictated by the internal implementation which includes member variable names.
In the past I used names like employeeName
, aName
, and theAlias
for parameters in such cases, but I disliked the artificial modifiers that ended up being used. If I could not use underscores for private variables I would use this.x
and not think twice about it.
1 Requiring this form is due to this
being "implicit" in C# and variable shadowing. That is, this.x
is needed because x
will refer to a local variable/parameter, should it exist - and it does here.
private string name;
public Employee(string name, string alias)
{
// Re-assignes parameter to itself.
// Does NOT assign member variable!
name = name;
}
2 I believe that underscore in names break "CLS-compatibility", but that is not a concern for me, and only using this convention for private member variables avoids exposing such incompatible names publicly.