Properties (C# vs Java)
In C#, a property is a named member of a class, struct, or interface offering a neat way to access private fields through what are called the get and set accessor methods.
The following code example declares a property called Species for the class Animal, which abstracts access to the private variable called species:
public class Animal
{
private string species;
public string Species
{
get
{
return species;
}
set
{
species = value;
}
}
}
Often, the property will have the same name as the internal member that it accesses, but with a capital initial letter, such as Species in the above case, or the internal member will have an _ prefix. Also, note the implicit parameter called value used in the set accessor; this has the type of the underlying member variable.
Accessors are in fact represented internally as get_X() and set_X() methods in order to maintain compatibility with the .NET Framework-based languages, which do not support accessors. Once a property is defined, it is then very easy to get or set its value:
class TestAnimal
{
static void Main()
{
Animal animal = new Animal();
animal.Species = "Lion"; // set accessor
System.Console.WriteLine(animal.Species); // get accessor
}
}
If a property only has a get accessor, it is a read-only property. If it only has a set accessor, it is a write-only property. If it has both, it is a read-write property.
See Also
Concepts
Reference
Properties (C# Programming Guide)