When is it appropriate to use expression bodied methods?
Zohar Peled

Zohar Peled @peledzohar

About: By day, try to work. By night, try to sleep.

Location:
Israel
Joined:
Sep 9, 2019

When is it appropriate to use expression bodied methods?

Publish Date: Dec 25 '19
7 5

C#6 introduced the concept of expression bodied members for methods and readonly properties, and c#7 expanded that concept further to also include constructors, finalizers, getters and setters.

Personally, it took me some time to get used to this concept, and for quite a long while I've avoided using expression bodied members.

In a recent project I've been working on, I've had to deal a lot with the file system, so I've created a class to wrap all the IO operations, to enable easy unit testing.
Since it's a simple wrapper class with almost no logic, most of the methods in this class are one liners - things like

    public void DeleteFile(string fullName)
    {
        File.Delete(fullName);
    }
Enter fullscreen mode Exit fullscreen mode

After writing a few of these methods, I've decided to change them to expression bodied, which makes them look like this:

    public void DeleteFile(string fullName)
        => File.Delete(fullName);
Enter fullscreen mode Exit fullscreen mode

Except in one-liners, where an expression bodied member seems like an obvious choice, where else is it appropriate to use that technique?

Comments 5 total

  • M.T
    M.TDec 26, 2019

    I think it's purpose is Readability.

  • Jonas Barkå
    Jonas BarkåDec 26, 2019

    Great question, I also wonder about this.

  • saint4eva
    saint4evaDec 28, 2019

    It can also be used in switch expression. Nice writeup.

    • Zohar Peled
      Zohar PeledDec 28, 2019

      Thanks! though I believe that c#7 doesn't support switch expressions - as far as I know they where introduced in c#8...

      • saint4eva
        saint4evaDec 28, 2019

        Yes, switch expression is a feature of C# 8. I was letting you know another scenario where it could be used - pattern matching

Add comment