Expression Bodied  Local Function in C# 7.0

Expression Bodied Local Function in C# 7.0

Expression-bodied methods” were introduced with C# 6.0, that simplify the syntactic expression for methods in C#.  C# 7.0 extend this features for several new members including constructor, destructor, property assessors etc, and we have seen this one of our previous post – Expression – Bodied Members in C# 7.0. C# 7.0, also introduced local function by defining the helper function with in the method itself – Helper function for your local method – Local Function in C# 7.0.

Now the question is – Can we use the Expression Bodied Members for Local Function?  Yes, You can!

Let’s consider the below example of Local Function.

static void Main(string[] args)
{
int val = 100;
int MyLocalFunction(int value1, int value2)
{
return val + value1 + value2;
}

Console.WriteLine(MyLocalFunction(10, 10));
}

 

Related Tip : Helper function for your local method – Local Function in C# 7.0

You can have this local method represented as Expression bodied method as shown in the below snippet.

static void Main(string[] args)
{
int val = 100;

int MyLocalFunction(int value1, int value2) => value1 + value2 + val;

Console.WriteLine(MyLocalFunction(10, 10));
}

Related Tip: Expression – Bodied Members in C# 7.0

Expression Bodied Local Function

Hope This helps !

Abhijit Jana

Abhijit runs the Daily .NET Tips. He started this site with a vision to have a single knowledge base of .NET tips and tricks and share post that can quickly help any developers . He is a Former Microsoft ASP.NET MVP, CodeProject MVP, Mentor, Speaker, Author, Technology Evangelist and presently working as a .NET Consultant. He blogs at http://abhijitjana.net , you can follow him @AbhijitJana . He is the author of book Kinect for Windows SDK Programming Guide.

One Comment to “Expression Bodied Local Function in C# 7.0”

Comments are closed.