Getter and Setter

Properties in a class protect the fields in a class. These properties by using the get and set methods
it helps the fields in reading and writing.

It basically encapsulates the fields. The private fields are exposed through properties.
The property contains a variable and methods. These methods get and set.

Example:

 

using System;
namespace SampleProgram {
  class MySample {
    private string strAddress;
    public string StrAddress // property as public
    {
      get {
        return name;
      } // get method to return value
      set {
        name = value;
      } // set method to update
    }
  }
}

 

There are 3 types of Properties in C#. These are:

- Read Only:

Read Only properties will have only the get method. To make the StrAddress a read-only property, in the above example remove the set method.

-  Write Only:

Write only properties will have only the set method. To make the StrAddress a write only property, in the above example remove the get method.

-  Both:

Here, we will have both get and set methods.

Example:

 

using System;
namespace SampleProgram {
  class MySample {
    private string strAddress;
    public string StrAddress // property as public
    {
      get {
        return name; } // get method to return value
      set {
        name = value;
      } // set method to update
    }
  }
  class Program {
    public static void Main(string[] args) {
      MySample obj = new MySample();
      obj.strAddress = “New Delhi, India”;
      Console.WriteLine($”Address is {obj.strAddress }”);
    }
  }
}

 

The output will be:

Address is New Delhi, India

 

Related Tutorials