Given the following code:-
private string name;
public string Name
{
get { return name; }
set { name = value; }
}
public string GetName()
{
return name;
}
public void SetName(string value)
{
name = value;
}
The first part is an example of an Automatic Get\Set property. The Get is returning the field value and the Set is setting the field value.
The second part is showing how the properties can be turned into methods to achieve the same thing.
My question is with that Constructors and Methods always seem to assign to Properties directly rather than the underlining fields as seen in the method examples GetName and SetName above? is the code just purely an example of how to achieve the same thing ie a like for like comparison?
Thanks
Steven
The first part is an example of an Automatic Get\Set property. The Get is returning the field value and the Set is setting the field value.
The second part is showing how the properties can be turned into methods to achieve the same thing.
My question is with that Constructors and Methods always seem to assign to Properties directly rather than the underlining fields as seen in the method examples GetName and SetName above? is the code just purely an example of how to achieve the same thing ie a like for like comparison?
Thanks
Steven
VulpesPosted Mar 30, 2012, 6:28 AM
So, it doesn't really matter whether a constructor or method within the same class accesses a property or its underlying field directly. However, in my experience, the latter is commoner than the former.
Sam HobbsPosted Mar 30, 2012, 2:12 PM
The advantages of properties are not obvious from simple examples. Properties are considered advantageous by experienced developers. If you were to develop an application system consisting of many programs that used fields directly (not using properties or methods such as GetName and SetName) and then later something needed to be done to the fields every timne the field is gotten or set then you will understand how much more efficient properrties would be for your time. It is developer's efficiency that is the consideration.