Last Updated on January 30, 2021 by sandeeppote

C# 6 Local functions are useful to create helper methods and was written as below-

 
public class LocalFunctions
{
    public int Age { get; set; }

    public string C6PrivateFunction()
    {
       return $"C#6 ==> Person is {GetEligibility(Age)}";
    }        
}

private string GetEligibility(int age)
{
   return age > 18 ? "Adult" : "Youth";
}

With C# 7.0 the same can be written as below.

Inside local functions, variables and parameters from the enclosing scope are also available and the same can also be written using as expression body.

        
public string C7LocalFunction()
{
   return $"C#7 ==> Person is {GenerateEligibility(Age)}";

   string GenerateEligibility(int age)
   {
      return age > 18 ? "Adult" : "Youth";
   }
}

public string C7LocalFunction1()
{
   return $"C#7 ==> Person is {GenerateEligibility(Age)}";

   string GenerateEligibility(int age) =>  age > 18 ? "Adult" : "Youth";
}

Enjoy coding!!!