This is my fifth article on C# 7. Followings are the links for my previous articles.
- Top 10 New Features of C# 7 With Visual Studio 2017
- Visual Studio 15 Preview First Look & C# 7
- How to Compile & Test C# 7 Features
- Understanding ref and out With C# 7
In C# 7, indexers and operator overloading can be written as expression bodied members.
Expression bodied indexers
In C# 7, Indexers can be written as expression bodied members called as “Expression bodied indexers”.
code snippet
- class MyFavColor
- {
- private Color[] favColor = new Color[] {Red, Green, Blue,Yellow, Orange};
- public string this[int index] => favColor[index].Name;
- }
Complete code with its usage
- using System.Drawing;
- using static System.Drawing.Color;
- using static System.Console;
- using Humanizer;
- using static Humanizer.OrdinalizeExtensions;
-
- namespace ExpressionBodiedIndexersExample
- {
- class Program
- {
- static void Main(string[] args)
- {
- MyFavColor myFavColor = new MyFavColor();
- WriteLine("My color preferences are :");
- for (int i = 0; i < 5; i++)
- {
- WriteLine($"{(i+1).Ordinalize()} : {myFavColor[i]}");
- }
- }
- }
-
- class MyFavColor
- {
- private Color[] favColor = new Color[] {Red, Green, Blue,Yellow, Orange};
- public string this[int index] => favColor[index].Name;
- }
-
- }
Output
Expression bodied Operators Overloading
In C# 7, operator overloading can be written as expression bodied members and called as “Expression bodied Operators Overloading”.
Code Snippet
- class Employee
- {
- public int Age { get; set; }
- public int Salary { get; set; }
- public static Employee operator ++(Employee emp) =>
- new Employee { Age = emp.Age + 1, Salary = emp.Salary + 2000 };
- }
Complete code
- using static System.Console;
-
- namespace ExpressionbodiedOperatorsExample
- {
- class Program
- {
- static void Main(string[] args)
- {
- Employee emp = new Employee { Age = 25, Salary = 80000 };
- emp++;
- WriteLine($"Age: {emp.Age}, Salary : {emp.Salary}");
- }
- }
-
- class Employee
- {
- public int Age { get; set; }
- public int Salary { get; set; }
- public static Employee operator ++(Employee emp) =>
- new Employee { Age = emp.Age + 1, Salary = emp.Salary + 2000 };
- }
- }
If you are looking for an example of other expression bodied members, such as - expression bodied methods, expression bodied properties, expression bodied constructor, expression bodied destructor, expression bodied getters & expression bodied setters, then you can visit here.