CSharp - Property Properties Definition

Introduction

Properties are fields with logics.

The following code get and set CurrentRadius from Circle.

Circle myCircle = new Circle();
myCircle.CurrentRadius = 30;
myCircle.CurrentRadius -= 3;
Console.WriteLine (myCircle.CurrentRadius);

CurrentRadius is like a field when you are using them.

A property is declared like a field, but with a get/set block added.

Here's how to implement CurrentRadius as a property:

class Circle
{
       decimal currentRadius;           // The private "backing" field

       public decimal CurrentRadius     // The public property
       {
         get { return currentRadius; }
         set { currentRadius = value; }
       }
}

get and set are property accessors.

get accessor runs when the property is read.

It must return a value of the property's type.

set accessor runs when the property is assigned.

It has an implicit parameter named value of the property's type that you typically assign to a private field(currentRadius).

Properties give the implementer complete control over getting and setting its value.

Modifiers

Properties allow the following modifiers:

Modifier Value
Static modifier static
Access modifierspublic internal private protected
Inheritance modifiers new virtual abstract override sealed
Unmanaged code modifiers unsafe extern

Related Topics