DEV Community

Zohar Peled
Zohar Peled

Posted on

When is it appropriate to use expression bodied methods?

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?

Top comments (5)

Collapse
 
saint4eva profile image
saint4eva

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

Collapse
 
peledzohar profile image
Zohar Peled

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

Collapse
 
saint4eva profile image
saint4eva

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

Collapse
 
mtmb profile image
M.T

I think it's purpose is Readability.

Collapse
 
jonasbarka profile image
Jonas Barkå

Great question, I also wonder about this.