Here is a quote from the offical microsoft docs...
https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/local-functions
Starting with C# 7.0, C# supports local functions. Local functions are private methods of a type that are nested in another member. They can only be called from their containing member.
Basically you can define a method inside a method. Your inner method can only be called by the parent method. They are, by definition, private and the compiler won't let you put an access modifier on it. As stated, this was added to C# in v7.0. The docs have a simple example which i have added a few lines to. I've marked thew additional lines with ******...
using System;
using System.IO;
namespace MyConsoleApp
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello Stackathon readers!");
Console.WriteLine(GetText("C:/Temp/Sample Files/simple", "company.csv"));
Console.Read();
}
private static string GetText(string path, string filename)
{
var methodVariable = "methodVariable set at the top of GetText method"; // ******
var sr = File.OpenText(AppendPathSeparator(path) + filename);
var text = sr.ReadToEnd();
Console.WriteLine(methodVariable); // ******
return text;
// Declare a local function.
string AppendPathSeparator(string filepath)
{
methodVariable = "methodVariable set inside AppendPathSeparator method"; // ******
if (!filepath.EndsWith(@"\"))
filepath += @"\";
return filepath;
}
}
}
}
The lines I've added are to prove a point. I've defined a variable called methodVariable inside the parent method. I've then modified the value of methodVariable inside the local method. Finally I've writen the value to the console. Running this will output "methodVariable set inside AppendPathSeparator method". Basically, our local method has the context of the parent method - it has full access to all the variables in the parent. This is a potential vector for bugs. Well, C# 8.0 has us covered with static local methods.
static string AppendPathSeparator(string filepath)
{
methodVariable = "methodVariable set inside AppendPathSeparator method"; // ******
if (!filepath.EndsWith(@"\"))
filepath += @"\";
return filepath;
}
Putting static in front of our local method isolates the local method from accessing variables from the parent methods context. The code above won't compile because the local method doesn't know what methodVariable is. It's also worth pointing out that our local method does have access to any static members of the Program class.
This isn't going to change the world but it's a nice little feature added in C# 8.0.
Top comments (3)
This is great! I'm learning something new every day.
I wonder about the reasoning behind allowing the standard local functions to access the parents variables.
I'm guess that it was simply easier to implement it that way. No need to manage a seperate context. Or maybe the compiler was restricted in 7.0. With static local functions with have the option of both.