Introducing Radical.sh

Forget Code launches a powerful code generator for building API's

Properties in C# - Study of SET and GET in C#

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.

  1. //MyClass.cs
  2. //Demonstrates a property
  3. class MyClass {
  4. MyType myInternalReference;
  5. //Begin property definition
  6. public MyType PropertyName{
  7. get {
  8. //logic
  9. return myInternalReference;
  10. }
  11. set{
  12. //logic
  13. myInternalReference = value;
  14. }
  15. }
  16. //End of property definition
  17. }//(Not intended to compile – MyType does not exist)

To use a Property, you access the name of the property directly:
  1. myClassInstance.MyProperty = someValue; //Calls "set"
  2. MyType t = myClassInstance.MyProperty; //Calls "get"