loading...

When is it appropriate to use expression bodied methods?

peledzohar profile image Zohar Peled ・1 min read

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);
    }

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);

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

Posted on by:

peledzohar profile

Zohar Peled

@peledzohar

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

Discussion

pic
Editor guide
 

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

 

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

 

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

 

I think it's purpose is Readability.

 

Great question, I also wonder about this.