C# Properties

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:

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.

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

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