Fields should, essentially, never be available directly to the outside world.
C# allows you to give your classes the appearance of having fields directly exposed but in fact hiding them behind method invocations.
These Property fields come in two varieties: read-only fields that cannot be assigned to, and the more common read-and-write fields.
Additionally, properties allow you to use a different type internally to store the data from the type you expose.
For instance,
you might wish to expose a field as an easy-to-use bool, but store it internally within an efficient BitArray class.
Properties are specified by declaring the type and name of the Property, followed by a bracketed code block that defines a get code block (for retrieving the value) and a set code block. Read-only properties define only a get code block.
The get code block acts as if it were a method defined as taking no arguments and returning the type defined in the Property declaration.
The set code block acts as if it were a method returning void that takes an argument named value of the specified type.
Here’s an example of a read-write property
called PropertyName of type MyType.
- //MyClass.cs
- //Demonstrates a property
- class MyClass {
- MyType myInternalReference;
- //Begin property definition
- public MyType PropertyName{
- get {
- //logic
- return myInternalReference;
- }
- set{
- //logic
- myInternalReference = value;
- }
- }
- //End of property definition
- }//(Not intended to compile – MyType does not exist)
To use a Property, you access the name of the property directly:
- myClassInstance.MyProperty = someValue; //Calls "set"
- MyType t = myClassInstance.MyProperty; //Calls "get"