Utilizor
Contact Us

C# Properties

Encapsulation using properties (get/set).

C# Properties (Get and Set)

Encapsulation is to make sure that "sensitive" data is hidden from users. To achieve this, you must:

  • declare fields/variables as private
  • provide public get and set methods, through properties, to access and update the value of a private field

Properties

A property is like a combination of a variable and a method, and it has two methods: a get and a set method:

class Person
{
  private string name; // field

  public string Name   // property
  {
    get { return name; }   // get method
    set { name = value; }  // set method
  }
}

The Name property is associated with the name field. It is a good practice to use the same name for both the property and the private field, but with an uppercase first letter.

Auto-Implemented Properties

C# also provides a way to use short-hand / automatic properties, where you do not have to define the field for the property, and you only have to write get; and set; inside the property.

class Person
{
  public string Name  // property
  { get; set; }
}

Examples

Using Properties

Get and Set methods in action.

using System;

class Person
{
  private string name; // field
  public string Name   // property
  {
    get { return name; }
    set { name = value; }
  }
}

class Program
{
  static void Main(string[] args)
  {
    Person myObj = new Person();
    myObj.Name = "Liam";
    Console.WriteLine(myObj.Name);
  }
}

Automatic Properties

Short-hand syntax.

using System;

class Person
{
  public string Name { get; set; }
}

class Program
{
  static void Main(string[] args)
  {
    Person myObj = new Person();
    myObj.Name = "Liam";
    Console.WriteLine(myObj.Name);
  }
}

Read-Only Property

Property with only get.

using System;

class Person
{
    private string name = "John";
    public string Name
    {
        get { return name; }
        // No set method
    }
}

class Program
{
    static void Main()
    {
        Person p = new Person();
        Console.WriteLine(p.Name);
        // p.Name = "Bob"; // Error: Property cannot be assigned to
    }
}