When is it appropriate to use expression bodied methods?
Zohar Peled
Posted on December 25, 2019
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 December 25, 2019
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.