C# 7 Local Functions

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!!!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s