Mega Code Archive

 
Categories / C# Book / 01 Language Basics
 

0121 Properties

Properties are fields with logics. C# uses get and set keywords to declare a property. using System; class Rectangle{ private int width; public int Width{ get{ return width; } set{ width = value; } } } class Program { static void Main(string[] args) { Rectangle r = new Rectangle(); r.Width = 5; Console.WriteLine(r.Width); } } The output: 5 get and set are called property accessors. get accessor is called when reading the property and set accessor is called when assigning value to the property. value is the parameter, which designates the value being assgined. A property can have the following modifier: static public internal private protected new virtual abstract override sealed unsafe extern