DEV Community

Juarez Júnior
Juarez Júnior

Posted on

C# Tip: Expression-bodied Members

Let’s talk about Expression-bodied Members, introduced in C# 6, which allow simplifying 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);
    }
}
Enter fullscreen mode Exit fullscreen mode

Explanation:
With Expression-bodied Members, you can define methods, properties, and operators more concisely, using the => syntax instead of full code blocks. 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 using Expression-bodied Members! Until next time.

Top comments (0)