This is my fifth article on C# 7. Followings are the links for my previous articles.

  1. Top 10 New Features of C# 7 With Visual Studio 2017
  2. Visual Studio 15 Preview First Look & C# 7
  3. How to Compile & Test C# 7 Features
  4. 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”.

C#

code snippet

  1. class MyFavColor
  2. {
  3. private Color[] favColor = new Color[] {Red, Green, Blue,Yellow, Orange};
  4. public string this[int index] => favColor[index].Name;
  5. }

Complete code with its usage

  1. using System.Drawing;
  2. using static System.Drawing.Color;
  3. using static System.Console;
  4. using Humanizer;
  5. using static Humanizer.OrdinalizeExtensions;
  6. namespace ExpressionBodiedIndexersExample
  7. {
  8. class Program
  9. {
  10. static void Main(string[] args)
  11. {
  12. MyFavColor myFavColor = new MyFavColor();
  13. WriteLine("My color preferences are :");
  14. for (int i = 0; i < 5; i++)
  15. {
  16. WriteLine($"{(i+1).Ordinalize()} : {myFavColor[i]}");
  17. }
  18. }
  19. }
  20. class MyFavColor
  21. {
  22. private Color[] favColor = new Color[] {Red, Green, Blue,Yellow, Orange};
  23. public string this[int index] => favColor[index].Name;
  24. }
  25. }

Output

C#

Expression bodied Operators Overloading

In C# 7, operator overloading can be written as expression bodied members and called as “Expression bodied Operators Overloading”.

C#

Code Snippet

  1. class Employee
  2. {
  3. public int Age { get; set; }
  4. public int Salary { get; set; }
  5. public static Employee operator ++(Employee emp) =>
  6. new Employee { Age = emp.Age + 1, Salary = emp.Salary + 2000 };
  7. }

Complete code

  1. using static System.Console;
  2. namespace ExpressionbodiedOperatorsExample
  3. {
  4. class Program
  5. {
  6. static void Main(string[] args)
  7. {
  8. Employee emp = new Employee { Age = 25, Salary = 80000 };
  9. emp++;
  10. WriteLine($"Age: {emp.Age}, Salary : {emp.Salary}");
  11. }
  12. }
  13. class Employee
  14. {
  15. public int Age { get; set; }
  16. public int Salary { get; set; }
  17. public static Employee operator ++(Employee emp) =>
  18. new Employee { Age = emp.Age + 1, Salary = emp.Salary + 2000 };
  19. }
  20. }

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.