Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialRa Bha
2,201 PointsWhy does the instructor change the name of the field Location to _location when the field changes to private?
Around 1:46 of the video, the instructor changes the name of the field Location to _location when the field changes to private. Are we then required to change the name of a field when the method access changes to private from public as a standard practice going forward?
Also, why does the name change when the field changes to private?
2 Answers
Wayne Mortenson
1,349 PointsThis is done purely because of naming conflicts with the private field and the constructor taking in a value in the parameter also named location, when instantiating the field. For example a person class that has a name field:
class Person { private readonly string name; public Person(string name) { name = name } } Here we have an issue with both things being called name. To solve this, we can use
this.name = name
where this is referring to the current objects field of name
or we can change
private readonly string name
to
private readonly string _name;
Philipp Räse
Courses Plus Student 10,298 PointsExactly as Wayne said, there are some so called "naming conventions".
That means, that some particular accessable variable should be written in a special kind.
Short example:
class Invader
{
// "private" variables are not accessable from outside the class and are shown by naming conventions with an "_" underscore infront of the lower-case first letter
private MapLocation _location;
// "public" variables are always written with an upper-case first letter.
public MapLocation Location
{
get
{
return _location;
}
set
{
_location = value;
}
}
}