Expression Bodied Members in C#

Introduction

In this section of the course, we have covered different ways to define methods and properties in C#. However, we have not yet explored a concise way to define simple members using a special syntax called Expression Bodied Members.

Rather than using the standard block syntax for methods and properties, Expression Bodied Members provide a more compact and readable way to write certain types of class members. This approach improves code clarity and makes the intent of the method or property more obvious.

This article will introduce Expression Bodied Members, explain why they are useful, provide a real-world analogy, and walk through their implementation with examples.


1. What Are Expression Bodied Members?

An Expression Bodied Member is a shorthand syntax in C# that allows defining simple methods, properties, or even constructors using the lambda arrow (=>) instead of curly braces { }.

This feature is useful when a method or property contains only a single expression, making the code cleaner and reducing unnecessary syntax.

Analogy

Imagine writing a short note versus a long letter. If you want to quickly remind a friend about a meeting, you could write:

Instead of writing:

Both say the same thing, but the first one is more concise and direct. Expression Bodied Members in C# work similarly – they let you express simple logic in fewer lines of code without unnecessary boilerplate.


2. Declaring and Using Expression Bodied Members

Expression Bodied Members can be used in methods, properties, constructors, finalizers, and even indexers.

Let's go through each case step by step.


2.1 Expression Bodied Methods

Normally, a method in C# is written like this:

class MathOperations
{
    public int Square(int number)
    {
        return number * number;
    }
}

Since this method only contains a single expression, we can simplify it using an Expression Bodied Member:

class MathOperations
{
    public int Square(int number) => number * number;
}

✔️ What changed?

This makes the code cleaner and more readable.


2.2 Expression Bodied Properties

If you have a read-only property, you can also use the same shorthand syntax.

Without Expression Bodied Members:

class Person
{
    private string name;

    public Person(string name)
    {
        this.name = name;
    }

    public string Name
    {
        get { return name; }
    }
}

With Expression Bodied Members:

class Person
{
    private string name;

    public Person(string name)
    {
        this.name = name;
    }

    public string Name => name; 
}

✔️ What changed?


2.3 Expression Bodied Constructors

Constructors can also use Expression Bodied syntax if they only contain a single statement.

Without Expression Bodied Syntax:

class Logger
{
    private string message;

    public Logger(string msg)
    {
        message = msg;
    }
}

With Expression Bodied Syntax:

class Logger
{
    private string message;

    public Logger(string msg) => message = msg;
}

✔️ What changed?


2.4 Expression Bodied Finalizers

Expression Bodied Members also work for finalizers, which are used for cleanup when an object is destroyed.

Without Expression Bodied Syntax:

class FileHandler
{
    ~FileHandler()
    {
        Console.WriteLine("Finalizer called!");
    }
}

With Expression Bodied Syntax:

class FileHandler
{
    ~FileHandler() => Console.WriteLine("Finalizer called!");
}

✔️ What changed?


2.5 Expression Bodied Indexers

Indexers allow objects to be indexed like arrays. Expression Bodied Members make indexers shorter when they contain a single return statement.

Without Expression Bodied Syntax:

class Collection
{
    private int[] numbers = { 1, 2, 3, 4, 5 };

    public int this[int index]
    {
        get { return numbers[index]; }
    }
}

With Expression Bodied Syntax:

class Collection
{
    private int[] numbers = { 1, 2, 3, 4, 5 };

    public int this[int index] => numbers[index];
}

✔️ What changed?


3. When to Use Expression Bodied Members?

✔️ Use them when methods or properties contain only a single expression.
✔️ They are best for readability and conciseness.
✔️ They are great for simple get-only properties, lightweight methods, constructors, finalizers, and indexers.


4. Best Practices and Common Mistakes

Best Practices

✔️ Use Expression Bodied syntax for simple operations.
✔️ Keep code concise but still readable.
✔️ Use it in conjunction with standard methods when necessary.

Common Mistakes

Using it for complex logic – If a method has multiple lines of code, stick to regular methods instead of Expression Bodied syntax.

// ❌ Not recommended for multiple expressions
public void Display()
{
    Console.WriteLine("Hello");
    Console.WriteLine("World");
}
// ❌ Incorrect usage of Expression Bodied syntax
public void Display() => Console.WriteLine("Hello"); Console.WriteLine("World"); // ERROR

✔️ Fix: Use standard method syntax for multi-line logic.


5. Conclusion

Expression Bodied Members allow you to write concise, readable, and efficient code by reducing unnecessary syntax. While they aren’t required for all methods or properties, they are an excellent tool for simplifying short, single-expression logic.

If you have any questions, feel free to ask in the Q&A section.
Happy coding! 🚀