CHAPTER 15

image

Properties

Properties in C# provide the ability to protect a field by reading and writing to it through special methods called accessors . They are generally declared as public with the same data type as the field they are going to protect, followed by the name of the property and a code block that defines the get and set accessors.

class Time{   private int seconds;    public int sec  {     get { return seconds; }    set { seconds = value; }  } } 

Properties are implemented as methods, but used as though they are fields.

static void Main(){   Time t = new Time();  int s = t.sec;} 

Note that the contextual value keyword corresponds ...

Get C# Quick Syntax Reference now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.