How to use get and set accessors in C#?

A thumbnail showing C# code.

How to use get and set accessors in C#?

To use get and set accessors in C#:

  1. Define the property accessor type and name. For example, public int Age.
  2. Add the get accessor body. The program executes the get body when we ready the property.
  3. (optional) Add the set accessor body. When we change the property, it executes the set body.

The third step is optional because we can have a read-only property.

csharp

public class Person
{
    private int _age;
    public int Age
    {
        get
        {
            return _age;
        }
        set
        {
            _age = value;
        }
    }
}
csharp
Person person = new ();

Console.WriteLine(person.Age); // 0
person.Age = 32;
Console.WriteLine(person.Age); // 32

What does { get; set; } mean in C#?

In C# classes it's very common to see { get; set; } code. The { get; set; } syntax in C# is a shorthand for the automatic property.

This syntax doesn't explicitly define bodies for get and set accessors:

csharp
public class Person
{
    public int Age {get; set;}
}

Instead, it provides a default implementation. This code is logically equivalent to:

csharp
public class Person
{
    private int _age;
    public int Age
    {
        get
        {
            return _age;
        }
        set
        {
            _age = value;
        }
    }
}

The only difference is that with automatic properties we cannot access the private variable.

That's because the compiler takes care of the implementation:

C# code for the get-set auto-implementation

Property initializers

C# 6.0 introduced property initializers. Property initializers let us define the default value for the automatic properties.

To use property initializers in C#:

  1. Define the property accessor type and name.
  2. Use the { get; set; } syntax.
  3. Pass the default value using the equal operator =;
csharp
public int Age { get; set; } = 10;

The default value of the property above is 10.

Read-only

To make the automatic property read-only, we omit the set modifier:

csharp
public int Age { get; } = 10;

In the code above, the Age property is now read-only.

We can only access it in the constructor:

csharp

public class Person
{
    public int Age { get; } = 10;

    public Person(int age)
    {
        Age = age; // this works! 
    }

    public void SetAge(int age)
    {
        Age = age; // won't work! Property or indexer 'Person.Age' cannot be assigned to -- it is read only
    }
}

Why we use properties in C#?

1. Data validation

The main use of properties is data validation. For example, we can add logic that prevents setting the age property to a negative value:

csharp

public int Age
{
    get
    {
        return _age;
    }
    set
    {
        if (value < 0)
            throw new ArgumentException("Age cannot be a negative number.")
        _age = value;
    }
}

2. Encapsulation

We use the private variable to hold the value locally. It provides encapsulation and lets us build the internal implementation without affecting outside code.

3. Raising events

Another use of get and set accessors in C# is raising events. We often want to perform action based on change. For example, "if order status changes to shipped, send an email". Set accessors are a great place to raise those events because they are the only point where object can change. So you don't have to duplicate the code by having it just before the setter call.

FAQ

What is encapsulation in C#?

In C#, encapsulation is a design principal that separates the external behavior from the internal implementation. We use encapsulation to group related logic in a meaningful way. For example, we can group customer information in a Customer object. That object can store information that we don't want other areas of code to access, for example, password. So, we use a combination of accessor properties and modifiers to define the level of encapsulation. It defines how accessible a piece of information should be.

Do private variables need to have underscore in C#?

Private variables in C# don't have to be named with underscore. Adding an underscore to the name of a private variable is a naming convention, but not a requirement. Your code will run without errors even if you don't use the underscore prefix.

Published on