Local Function And Default Interface Method - C# 6 To C# 9 New Features - Day Three

Introduction 
 
This article covers method changes and syntax improvements done in the newer version of C#, which includes local functions, static local function, and default interface methods. This article is the third article of the series, and below is the link for my previous articles. It is highly recommended to go through the previous articles to have a better understanding.
The following is a list of features that we are going to cover in this article:
 
C# 7.0
 
Local function or nested function
 
C# 8.0
  • Static local functions
  • Default interface methods
C# 9.0*: Proposed Method Enhancement
 
Permit attributes on local functions (proposed in C# 9.0)
 

Default Interface Method

 
In C# 8.0 and onwards, we can create a default interface method, (i.e., a method inside the interface can have an implementation). In other words, we can say that in C# 8.0 and onwards, an interface can contain a concrete method (method implementation) along with abstract methods.
 
So we can have an interface like shown below:
  1. interface IUser  
  2. {  
  3.     bool AddUser()  
  4.     {  
  5.         bool isAdded = false;  
  6.         //code to add a user  
  7.         return isAdded;  
  8.     }  
  9. }  
And we can call the default interface method through an object as well. Following is the complete code:
  1. namespace DefaultMethodExample  
  2. {  
  3.     class Program  
  4.     {  
  5.         static void Main()  
  6.         {  
  7.             IUser user = new User();  
  8.             user.AddUser();  
  9.         }  
  10.     }  
  11.   
  12.     interface IUser  
  13.     {  
  14.         //Default method inside an interface  
  15.         bool AddUser()  
  16.         {  
  17.             bool isAdded = false;  
  18.             //code to add a user  
  19.             return isAdded;  
  20.         }  
  21.     }  
  22.     class User : IUser  
  23.     {  
  24.         //AddUser() is a default interface method  
  25.         //so it is not necessary to implement it.  
  26.     }  
  27. }  
The above code snippet is just an example of how a default interface method works.
 

When do we need a Default Interface Method?

 
Let's take a real scenario where we may need a default interface method.
 
An interface with some abstract methods:
  1. interface IUser  
  2.     {  
  3.         bool AddUser();  
  4.         bool DeleteUser();  
  5.         string GetUserDetails();  
  6.     }  
An Existing Client which Implements the IUser interface:
  1. class ExistingUser : IUser  
  2.     {  
  3.         public bool AddUser() =>  
  4.             //code to add a user  
  5.             true;  
  6.   
  7.         public bool DeleteUser() =>  
  8.             //code to delete a user  
  9.             true;  
  10.   
  11.         public string GetUserDetails()  
  12.         {  
  13.             string userDetails = string.Empty;  
  14.             //code to get a user details  
  15.             return userDetails;  
  16.         }  
  17.     }  
New Requirement
 
Add a new Method Inside the existing interface to get the social media details of a user. The new interface will have the following code:
  1. interface IUser  
  2.     {  
  3.         bool AddUser();  
  4.         bool DeleteUser();  
  5.         string GetUserDetails();  
  6.         string GetSocialMediaDetails();  
  7.     }  
It is decided that whoever is a new client who implements IUser can have their own implementation for all the methods. But it will not work because we already have a client who is using the current version of the interface so we cannot add a new method inside the interface; otherwise, no longer the existing client would be able to use it. So, in this case, we need to think about another alternative such as introducing a new interface for new clients or some other techniques. Here the “default interface method” can be one of the best solutions by which we can add a new method inside the interface without disturbing the existing client.
 
Following is the complete code using a console application:
 
IUser.cs
  1. namespace DefaultMethodExample  
  2. {  
  3.     interface IUser  
  4.     {  
  5.         bool AddUser();  
  6.         bool DeleteUser();  
  7.         string GetUserDetails();  
  8.         string GetSocialMediaDetails() => "There is no social media details available for old client.";  
  9.     }  
  10. }  
 ExistingUser.cs
  1. namespace DefaultMethodExample  
  2. {  
  3.     //This is an existing client, and it will not implement the method GetSocialMediaDetails()  
  4.     //It will use the method implementation of the interface.  
  5.     class ExistingUser : IUser  
  6.     {  
  7.         public bool AddUser() =>  
  8.             //code to add a user  
  9.             true;  
  10.   
  11.         public bool DeleteUser() =>  
  12.             //code to delete a user  
  13.             true;  
  14.   
  15.         public string GetUserDetails()  
  16.         {  
  17.             string userDetails = string.Empty;  
  18.             //code to get a user details  
  19.             return userDetails;  
  20.         }  
  21.     }  
  22. }  
 NewUser.cs
  1. namespace DefaultMethodExample  
  2. {  
  3.     class NewUser : IUser  
  4.     {  
  5.         public bool AddUser() =>  
  6.             //code to add a user  
  7.             true;  
  8.   
  9.         public bool DeleteUser() =>  
  10.             //code to delete a user  
  11.             true;  
  12.   
  13.         //This is a new client so it will use its own  
  14.         //implementation for GetSocialMediaDetails() method.  
  15.         public string GetSocialMediaDetails() =>  
  16.             //code to get details  
  17.             "Twitter URL: @....";  
  18.   
  19.         public string GetUserDetails()  
  20.         {  
  21.             string userDetails = string.Empty;  
  22.             //code to get details  
  23.             return userDetails;  
  24.         }  
  25.     }  
  26. }  
 Program.cs
  1. using static System.Console;  
  2. namespace DefaultMethodExample  
  3. {  
  4.     class Program  
  5.     {  
  6.         static void Main()  
  7.         {  
  8.             IUser existingUser = new ExistingUser();  
  9.             WriteLine(existingUser.GetSocialMediaDetails());  
  10.   
  11.             IUser newUser = new NewUser();  
  12.             WriteLine(newUser.GetSocialMediaDetails());  
  13.         }  
  14.     }  
  15. }  
The default interface method would be beneficial when we need to extend an existing interface or if we need to implement versioning for an API service, where we can serve both new and existing clients using the same interface without changing the existing client code.
 

Local Function (Nested Function)

 
In the earlier version of C# until C# 6.0, we could have a nested class, but we could not have a nested function. However, from C# 7.0 onwards, we can have nested function as well. This nested function is more commonly referred to as local Function in C#.
 
The following code is an example of a local function:
  1. static void Main()  
  2. {  
  3.     var result = Sum(5, 7);  
  4.     int Sum(int x, int y)  
  5.     {  
  6.         return x + y;  
  7.     }  
  8. }  
 Many times the question of why we need a local function arises. This is because:
  1. There are multiple cases where we only need to use a method once. So we can make that method local to make it more readable and clarify the intent.
  2. In many cases, a local function is far better than a recursive function, as it does not need to maintain the call stack.

Making a local function for single referenced method

Have a look at the below code snippet:
  1. public class Offer  
  2.     {  
  3.         public void ShowOfferDeatils()  
  4.         {  
  5.             //Omitted for brevity  
  6.             var couponCode=GetCouponCode();  
  7.             Console.WriteLine(couponCode);  
  8.         }  
  9.   
  10.         private string GetCouponCode() => "Off" + new Random().Next();  
  11.   
  12.     }  
As we can see in the above code snippet that the function “GetCouponCode()” is being used only once. So we can move it inside the same method from where it is being called. So the above code can be re-written as follows,
  1. public class Offer  
  2.     {  
  3.         public void ShowOfferDeatils()  
  4.         {  
  5.             //Omitted for brevity  
  6.             var couponCode = GetCouponCode();  
  7.             Console.WriteLine(couponCode);  
  8.      //local function  
  9.             string GetCouponCode() => "Off" + new Random().Next();  
  10.         }  
  11.     }  

Local function performance over a recursive function

 
We know that if we call a recursive function, then a call stack is being maintained, In case of a local function, no call stack is being maintained, so it will always be faster than a recursive function call.
 
Let us have a look at the code below to compare the performance:
  1. using System.Numerics;  
  2. using System.Diagnostics;  
  3. using static System.Console;  
  4.   
  5. namespace LocalFunctionExample  
  6. {  
  7.     class Program  
  8.     {  
  9.         static void Main()  
  10.         {  
  11.             int x = 8500;  
  12.             Stopwatch watchRecursive = new Stopwatch();  
  13.             watchRecursive.Start();  
  14.             _ = Factorial(x);  
  15.             watchRecursive.Stop();  
  16.   
  17.             Stopwatch watchLocal = new Stopwatch();  
  18.             watchLocal.Start();  
  19.             _ = FactorialLocal(x);  
  20.             watchLocal.Stop();  
  21.   
  22.             WriteLine($"Time taken to calculate factorial of {x}");  
  23.             WriteLine($"Using recursive function: {watchRecursive.Elapsed.TotalMilliseconds}");  
  24.             WriteLine($"Using local function: {watchLocal.Elapsed.TotalMilliseconds}");  
  25.         }  
  26.   
  27.   
  28.         private static BigInteger FactorialLocal(int x)  
  29.         {  
  30.             //Omitted for brevity  
  31.             if (x == 0) return 1;  
  32.             BigInteger result = x;  
  33.             while (x > 1)  
  34.             {  
  35.                 x--;  
  36.                 Multiply();  
  37.             }  
  38.             void Multiply() => result *= x;  
  39.             return result;  
  40.         }  
  41.         private static BigInteger Factorial(int x) =>  
  42.             //Omitted for brevity  
  43.             x == 0 ? 1 : x * Factorial(x - 1);  
  44.     }  
  45. }  
Local Function And Default Interface Method - C# 6 To C# 9 New Features
 
In the above screenshot, we can see that a local function call is almost 10 times faster than a recursive function call.
 
We know that we can calculate the factorial value without using a recursive function as well. But here, my purpose is only to compare the performance difference; that is why we have taken it as an example.
 

A Few Questions about Local Functions

 
1. Can I get a Stackoverflow exception due to a local method call?
 
No. it does not maintain call stack, so we do not get stack overflow exception due to local method call.
 
2. Can we have an abstract local function?
 
No, we cannot have an abstract local function.
  1. static void Main()  
  2. {  
  3.     int Sum();  
  4. }  
Compilation Error
 
Error CS8112: 'Sum()' is a local function and must therefore always have a body.
 
3. Can we have a local function with multiple levels of nesting?
 
Yes. We can have a local function with multiple levels of nesting. Have a look at the code snippet below:
  1. class Program  
  2.     {  
  3.         //Method at First level  
  4.         static void Main()  
  5.         {  
  6.             //Local function  
  7.             void Calculate(int x, int y)  
  8.             {  
  9.                 //Local function inside a local function  
  10.                 int Add()  
  11.                 {  
  12.                     return x + y;  
  13.                 }  
  14.   
  15.                 //Local function inside a local function  
  16.                 int Diff()  
  17.                 {  
  18.                     return x - y;  
  19.                 }  
  20.             }  
  21.         }  
  22.     }  
4. Can we have an access modifier for a local function?
 
No. Access modifiers, e.g. private, public, protected, internal, private protected, and protected internal access modifiers are not allowed with local function. This is because it will be accessed only by the parent method in which it has been written, so there is no need to provide an accessibility modifier on it.
 
There are some cases for local functions that we are not going to cover in this article. If you would like to learn more about a local function and C# 7 new features, you can go through the article below.

Static Local Function

 
The Static Local Function is a new feature introduced with C# 8.0. Before C# 8.0, we could not have a local function as a static function.
 
In C# 7.x the below code does not get compiled.
  1. static void Main()  
  2.         {  
  3.             var result = Sum(5, 7);  
  4.             static int Sum(int x, int y)  
  5.             {  
  6.                 return x + y;  
  7.             }  
  8.         }  
Error: CS0106 The modifier 'static' is not valid for this item.
 
Whereas in C# 8.0, the above code gets compiled successfully. But as we know that there are some conditions with static function, so those conditions also apply with local static function. The last code example we have taken can also be re-written as shown below:
  1. static void Main()  
  2. {  
  3.     int x = 5, y = 7;  
  4.     var result = Sum();  
  5.     int Sum() => x + y;  
  6. }  
So in the above code snippet, we can see that we are using the parent method variable in a local function and these variables are non-static variables. But if we try to put a static keyword with the local function, which is accessing variables of parent method, then it will not work. The following is the screenshot for this principle.
 
 
Local Function And Default Interface Method - C# 6 To C# 9 New Features

Permit attributes on local functions (proposed in C# 9.0)

 
We have seen so far that local functions were introduced with C# 7.0. Later on, enhancement is done in C# 8.0 to allow a static variable. But it still has some restrictions.
 
Until C# 8.0, we could not use attributes with a “local function”.
  1. using System;  
  2. using System.Diagnostics;  
  3.   
  4. namespace StaticLocalFunctionExample  
  5. {  
  6.     class Program  
  7.     {  
  8.         static void Main()  
  9.         {  
  10.             Sum(8, 11);  
  11.           
  12.         [Conditional("DEBUG")]  
  13.         static void Sum(int x, int y)  
  14.             {  
  15.                 Console.WriteLine(x + y);  
  16.             }  
  17.         }  
  18.     }  
  19. }  
The above code does not get compiled up to C# 8.0. But in C# 9, there is a proposal to allow attribute with local function.

Summary

In this article, we have covered the following topics:
  1. Local function or nested function (C# 7.0).
  2. Making local functions for single referenced method.
  3. Local function performance over a recursive function.
  4. Reduce call stack using a local function.
  5. Static local functions (C# 8.0).
  6. Default interface methods (C# 8.0).
  7. When do we need a Default Interface Method?
  8. Permit attributes on local functions (proposed in C# 9.0).