
Expression-bodied accessors, constructors, and finalizers
If the following expression looks intimidating, it's because it is using a feature introduced in C# 6 and expanded in C# 7:
private HashSet<string> AllowedExtensions => new HashSet<string>(StringComparer.InvariantCultureIgnoreCase) { ".doc",".docx",".pdf", ".epub" }; private enum Extention { doc = 0, docx = 1, pdf = 2, epub = 3 }
The preceding example returns a HashSet of allowed file extensions for our application. These have been around since C# 6, but have been extended in C# 7 to include accessors, constructors, and finalizers. Let's simplify the examples a bit.
Assume that we had to modify the Document class to set a field for _defaultDate inside the class; traditionally, we would need to do this:
private DateTime _defaultDate; public Document() { _defaultDate = DateTime.Now; }
In C# 7, we can greatly simplify this code by simply doing the following:
private DateTime _defaultDate; public Document() => _defaultDate = DateTime.Now;
This is perfectly legal and compiles correctly. Similarly, the same can be done with finalizers (or deconstructors). Another nice implementation of this is expression-bodied properties as seen with the AllowedExtensions property. The expression-bodied properties have actually been around since C# 6, but who's counting?
Suppose that we wanted to just return the string value of the Extension enumeration for PDFs, we could do something such as the following:
public string PDFExtension { get { return nameof(Extention.pdf); } }
That property only has a get accessor and will never return anything other than the string value of Extension.pdf. Simplify that by changing the code to:
public string PDFExtension => nameof(Extention.pdf);
That's it. A single line of code does exactly the same thing as the previous seven lines of code. Falling into the same category, expression-bodied property accessors are also simplified. Consider the following 11 lines of code:
public string DefaultSavePath { get { return _jsonPath; } set { _jsonPath = value; } }
With C# 7, we can simplify this to the following:
public string DefaultSavePath { get => _jsonPath; set => _jsonPath = value; }
This makes our code a lot more readable and quicker to write. Swing back to our AllowedExtensions property; traditionally, it would be written as follows:
private HashSet<string> AllowedExtensions { get { return new HashSet<string>
(StringComparer.InvariantCultureIgnoreCase) { ".doc",
".docx", ".pdf", ".epub" }; } }
Since C# 6, we have been able to simplify this, as we saw previously. This gives developers a great way to reduce unnecessary code.