A new feature introduced with the release of C# 7.0 is Expression Bodies. This feature makes your code more readable and can reduce the number of lines of code drastically.
There are 3 types of Expression Bodies introduced in C# 7.0 -
Accessor
Generally, while declaring properties, we use the Get as well as Set accessor and these are used to return and set the value a private member. For the Get accessor, we just return a private member. For this, we generally have a code block with {} braces and in between, we write a written statement. For this, it will take 3 to 4 lines of code. Do we really need this? Of course, no! In C# 7.0, now we can reduce such implementation in one line. Similarly, we can do that for Set Accessor.
Constructor
The same as above, here, we can have small constructors (injecting one or two variables to class properties) in 1 or 2 lines instead of 5 to 6 lines of code.
Finalizer
I hope I have no need to explain this too. It is understood that we can cut short even the Finalizer, or we can say destructors.
Now, we can go into action. Below is the code snippet of what we used to do before C# 6.0.
- public class ExpressionBodiesOld {
- private string _myName;
- public string MyName {
- get {
- return _myName;
- }
- set {
- if (value != null) _myName = value;
- else throw new ApplicationException("Cannot be null");
- }
- }
- public ExpressionBodiesOld(string name) {
- MyName = name;
- }~ExpressionBodiesOld() {
- Console.WriteLine("Released");
- }
- }
As observed, it took almost 28 lines. Now, mentioned below is the simplified code of the above by applying Expression Bodies feature which took 18 lines of code. So, we saved 10 lines of code with more readability.
- public class ExpressionBodies {
- private string _myName;
- public string MyName {
-
- get => _myName;
-
- set => _myName = value ? ?
- throw new ApplicationException("Cannot be null");
- }
-
- public ExpressionBodies(string name) => MyName = name;
-
- ~ExpressionBodies() => Console.WriteLine("Released");
- }
I hope this explanation gives you the concept.
You can see the complete code here on GitHub.
Happy Coding :)