close
close

C# Tip: Members with Expression Bodies – DEV Community

C# Tip: Members with Expression Bodies – DEV Community

Let’s talk about Expression-bodied Members, introduced in C# 6, which allow to simplify the syntax of methods, properties and other members that return a value. See the example in the code below.

public class Product
{
    public string Name { get; set; }
    public decimal Price { get; set; }

    // Using Expression-bodied Member for the ToString method
    public override string ToString() => $"Product: {Name}, Price: {Price:C}";
}

public class Program
{
    public static void Main()
    {
        var product = new Product { Name = "Pen", Price = 2.99m };
        Console.WriteLine(product);
    }
}
Go to full screen mode

Exit full screen

Explanation:
Expression-bodied Members allow you to define methods, properties, and operators more concisely, using the => syntax instead of entire blocks of code. This is especially useful for members that consist of a single line of code, making the code cleaner and easier to read. In the example above, we show how to simplify the definition of a ToString method using this syntax.

Source code: GitHub

I hope this tip helps you make your code more concise and readable with Expression-bodied Members! Until next time.