Hints to solve name conflicts between params & fields

  • Thread starter Thread starter Javier Venero
  • Start date Start date
J

Javier Venero

I would like to know from the experienced C# programmers witch is the best
approach to solve name conflicts between function parameters & fields.

Option A (using this):

class Foo
{
string name;

public Foo(string name)
{
this.name = name;
}
}

Option B: (using m_ prefix):

class Foo
{
string m_name;

public Foo(string name)
{
m_name = name;
}
}

Option C: (no using parameters with the same name that class fields)
 
Javier Venero said:
I would like to know from the experienced C# programmers witch is the best
approach to solve name conflicts between function parameters & fields.

Option A (using this):

class Foo
{
string name;

public Foo(string name)
{
this.name = name;
}
}

Option B: (using m_ prefix):

class Foo
{
string m_name;

public Foo(string name)
{
m_name = name;
}
}

I think you'll find opinion is pretty divided on this. I personally use
the first version, but I know various others use the second.

I commonly end up with code such as:

string name;
/// <summary>
/// The name of the person.
/// </summary>
public string Name
{
get { return name; }
set { name = value; }
}
 
Javier said:
I would like to know from the experienced C# programmers witch is the best
approach to solve name conflicts between function parameters & fields.

[...]

I use A, for two reasons:

1) It looks nicer than an ugly "m_" prefix.

2) It helps me to ensure that my methods don't get too long. I believe
that if you *really* need a prefix to be able to understand that code
in a particular method accesses a /member variable/, the method is
too long/complex and needs to be refactored.

<d&r>
 
I agree with you.
I was exploring other possibilities, because it is easy to forget the
"this." and the compiler does not say nothing.
Using m_ prefix sistematically could prevent this kind of misses, altough
it is ugly indeed.
I know that this kind of error is very stupid but sometimes the more stupid
the bug is the more is the time to find it :(
It would be desireable that the compiler issued warnings when a self
assignation is detected (perhaps it already does it but I don't know).
Thanks a lot to all.


C# Learner said:
Javier said:
I would like to know from the experienced C# programmers witch is the best
approach to solve name conflicts between function parameters & fields.

[...]

I use A, for two reasons:

1) It looks nicer than an ugly "m_" prefix.

2) It helps me to ensure that my methods don't get too long. I believe
that if you *really* need a prefix to be able to understand that code
in a particular method accesses a /member variable/, the method is
too long/complex and needs to be refactored.

<d&r>
 
Back
Top