Get to know Properties - CSharp Custom Type

CSharp examples for Custom Type:Property

Introduction

Properties look like fields from the outside, but internally they contain logic, like methods do.

A property is declared like a field, but with a get/set block added. Here's how to implement CurrentPrice as a property:

public class Stock
{
 decimal currentPrice;           // The private "backing" field

 public decimal CurrentPrice     // The public property
 {
   get { return currentPrice; }
   set { currentPrice = value; }
 }
}

get and set denote property accessors.

The get accessor runs when the property is read.

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

The 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.

Properties allow the following modifiers:

Modifier Value
Static modifierstatic
Access modifiers public internal private protected
Inheritance modifiers new virtual abstract override sealed
Unmanaged code modifiersunsafe extern

Related Tutorials