[C#] Concisely Defining Property Get/Set Accessors Using Expression Bodies (=>)

Since C# 7.0, you can write both property get and set accessors as “expression-bodied members.”

This allows you to simply write property definitions using the arrow operator =>, replacing the traditional block { ... } and return statements. This reduces the amount of code for simple read/write operations or properties with one-line logic, improving readability.

In this article, I will explain how to implement properties containing validation logic using the expression body syntax, using a user management class as an example.

目次

Table of Contents

  1. Implementation Example: Property with Validation
  2. Explanation
  3. Summary

Implementation Example: Property with Validation

The following code implements logic to automatically assign a default value when null is attempted to be set to the UserName property. Note that both get and set are written in the expression body style.

using System;

namespace ExpressionBodiedPropertyExample
{
    class Program
    {
        static void Main(string[] args)
        {
            var user = new UserProfile();

            // 1. Set a normal value
            user.UserName = "Alice";
            Console.WriteLine($"Set Value: {user.UserName}");

            // 2. Set null (Logic in set accessor triggers)
            user.UserName = null;
            Console.WriteLine($"Value after setting null: {user.UserName}");
        }
    }

    public class UserProfile
    {
        // Backing field (variable that actually holds the value)
        private string _userName = "Unknown User";

        public string UserName
        {
            // get accessor: returns the field value as is
            // Traditional: get { return _userName; }
            get => _userName;

            // set accessor: assigns default value if null, otherwise assigns the value
            // Traditional: set { _userName = value ?? "Guest"; }
            set => _userName = value ?? "Guest";
        }
    }
}

Explanation

1. Syntax Simplification

In C# 6.0, only get accessors supported expression bodies, but since C# 7.0, set accessors can be written in the same way.

  • Get: get => expression; returns the result of the expression (implicit return).
  • Set: set => expression; executes the expression. You can write assignment expressions or method calls on the right side.

2. Combination with Null-Coalescing Operator

The value ?? "Guest" in the code example concisely represents the logic: “If the value being assigned (value) is null, use 'Guest' instead.”

set accessors containing simple guard clauses or conversion logic like this are a great match for expression bodies.


Summary

Using expression-bodied property definitions allows you to reduce boilerplate code and highlight the essential part of the logic.

  • Simple Wrapper: get => _field; set => _field = value;
  • Processing Values: set => _field = value.Trim();

However, if complex processing spanning multiple lines is required, it is recommended to use the traditional block { ... } to maintain readability rather than forcing the expression body syntax.

よかったらシェアしてね!
  • URLをコピーしました!
  • URLをコピーしました!

この記事を書いた人

私が勉強したこと、実践したこと、してることを書いているブログです。
主に資産運用について書いていたのですが、
最近はプログラミングに興味があるので、今はそればっかりです。

目次