C# properties are the class members that provide a flexible way for the class to expose its private field. It provides a way to read, write, and perform some computation to the private fields of the class.
These properties have special methods called accessors that are used to set, get, and compute on private fields of the class. The two accessors used are the get accessor and set accessor.
- get accessor: It specifies read-only property and returns a property value. We use it to get the private filed value as a public.
- set accessor: It specifies write-only property and returns a property value. We use it to assign a new value to the private filed.
The properties can be read-only, write-only, or read-write property. The read-only implements get an accessor but no set accessor. The write-only implements set accessor but no get accessor whereas read-write implements both set and get accessors.
We use it in the following way in a program:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | private String name; private int age; // Name as a String type public string Name { get { return name; } set { name = value; } } // Age as an int type public int Age { get { return age; } set { age = value; } } |
Let us go through a program to understand its use.
Example 1: C# program for Properties
We will write a program for a read-write property using a set and get accessors.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 | using System; public class Student { // private variables private String name; private int roll; // using setter and getter for name public String stdName { get { return name; } set { name = value; } } // using setter and getter for roll public int stdRoll { get { return roll; } set { roll = value; } } } class StudentInfo { static public void Main() { // creating object Student obj = new Student(); //setting the values obj.stdName = "John Mac"; obj.stdRoll = 15; // Getting the values Console.WriteLine("Student Name: " + obj.stdName); Console.WriteLine("Studen Roll: " + obj.stdRoll); } } |
Output:
Student Name: John Mac
Studen Roll: 15
Example 2: C# program for read-only Properties
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 | using System; public class Student { // private variables private String name; private int roll; public Student(String n, int r) { name = n; roll = r; } // using get public String stdName { get { return name; } } // using get public int stdRoll { get { return roll; } } } class StudentInfo { static public void Main() { // creating object Student obj = new Student("Jacob Hill", 17); // Getting the values Console.WriteLine("Student Name: " + obj.stdName); Console.WriteLine("Studen Roll: " + obj.stdRoll); } } |
Output:
Student Name: Jacob Hill
Studen Roll: 17