Is it a field or a property?
I very much value code reviews, as long time readers can attest. During these reviews, I have often found myself wondering whether a given line references a field or a property. When reading isolated portions of code, properties can be easily mistaken for fields.
Player player = new Player("Someone");String name = player.Name;player.Age = 22;
By looking at only the two lines above, is it possible to tell, conclusively, whether or not Name and Age are properties or fields on the Player object? I assert that it is not. Let's take a closer look at fields and properties.
A field is a variable exposed by the object.
public class Player{ public String Name; public Int32 Age;}
Properties are methods (a getter and/or a setter).
public class Player{ private String m_Name; public String Name { get{ return this.m_Name; } } private Int32 m_Age; public Int32 Age { get{ return this.m_Age; } set { if( 18 >= value ) { throw new ArgumentException("Player must be at least 18 years old."); } this.m_Age = value; } }}
Each of the above examples would allow for code that looks like the original client snippet.
I typically use properties, in part, because they provide my client code with the same easy to use syntax for setting and retrieving values from a class that I get from fields with the added benefit of data validation when setting the value.
Take care,
-- DK
[Edit: fix error in example]
[Edit: add "m_" to private class members]
Disclaimers:
This posting is provided "AS IS" with no warranties, and confers no rights.