Embedded local functions in C# 7.0

Occasionally it happens that we want to group related code within a function without creating another private function for that. C# 7.0 provides a neat way for that in the form of local functions which are functions within functions.

Consider the following example:

public class LocalFunctionsDemo
{
	public void RunDemo()
	{
		int GetDiff(DateTime first, DateTime second)
		{
			TimeSpan ts = (second - first).Duration();
			return Convert.ToInt32(ts.TotalDays);
		}

                int dayDiff = GetDiff(DateTime.UtcNow, DateTime.UtcNow.AddHours(10));
			
		Console.WriteLine(dayDiff);
	}
}

Note how GetDiff lies within the boundaries of the RunDemo method. It can only be called from within the declaring function and not from anywhere else, not even from within the containing class. In this sense GetDiff is sort of a super-private function with a very limited scope.

Curiously we can call local functions BEFORE they are declared. The following code is still valid:

public void RunDemo()
{
	int dayDiff = GetDiff(DateTime.UtcNow, DateTime.UtcNow.AddHours(10));

	int GetDiff(DateTime first, DateTime second)
	{
		TimeSpan ts = (second - first).Duration();
		return Convert.ToInt32(ts.TotalDays);
	}
			
	Console.WriteLine(dayDiff);
}

View all various C# language feature related posts here.

Advertisement

About Andras Nemes
I'm a .NET/Java developer living and working in Stockholm, Sweden.

2 Responses to Embedded local functions in C# 7.0

  1. Can you give an example when somebody should use this kind of function ? When is justified to use embedded local functions ?

    • Andras Nemes says:

      I admit that it’s a bit difficult to give an example where this is the “absolute” solution. I can think of the following scenario: if someone looks at a class and reads the signatures of the various methods, both public and private, they can discover the interface and inner workings of the class. Occasionally though you may not want to reveal even that much and rather group a small section of reusable bit of code within a containing class. Also, local functions cannot even be directly executed through reflection.
      //Andras

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 )

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

Elliot Balynn's Blog

A directory of wonderful thoughts

Software Engineering

Web development

Disparate Opinions

Various tidbits

chsakell's Blog

WEB APPLICATION DEVELOPMENT TUTORIALS WITH OPEN-SOURCE PROJECTS

Once Upon a Camayoc

Bite-size insight on Cyber Security for the not too technical.

%d bloggers like this: