In C# 7.0, local functions are introduced. The local function allows you to declare a method inside the body of an already defined method. Or in other words, we can say that a local function is a private function of a function whose scope is limited to that function in which it is created. The type of local function is similar to the type of function in which it is defined. You can only call the local function from their container members.
Example:
C#
using System;
class Program {
public static void Main()
{
void SubValue( int a, int b)
{
Console.WriteLine( "Value of a is: " + a);
Console.WriteLine( "Value of b is: " + b);
Console.WriteLine( "final result: {0}" , a - b);
Console.WriteLine();
}
SubValue(30, 10);
SubValue(80, 60);
}
}
|
Output:
Value of a is: 30
Value of b is: 10
final result: 20
Value of a is: 80
Value of b is: 60
final result: 20
But in C# 7.0 you are not allowed to use static modifier with local function or in other words you are not allowed to create a static local function. This feature is added in C# 8.0. In C# 8.0, you are allowed to use a static modifier with the local function. This ensures that the static local function does not reference any variable from the enclosing or surrounding scope. If static local function tries to access the variable from the enclosed scope, then the compiler will throw an error. Let us discuss this concept with the help of the given examples:
Example 1:
C#
using System;
class Program {
public static void Main()
{
void AreaofCircle( double a)
{
double ar;
Console.WriteLine( "Radius of the circle: " + a);
ar = 3.14 * a * a;
Console.WriteLine( "Area of circle: " + ar);
circumference(a);
static void circumference( double radii)
{
double cr;
cr = 2 * 3.14 * radii;
Console.WriteLine( "Circumference of the circle is: " + cr);
}
}
AreaofCircle(30);
}
}
|
Output:
Radius of the circle: 30
Area of circle: 2826
Circumference of the circle is: 188.4
Example 2:
C#
using System;
class Program {
public static void Main()
{
void AreaofCircle( double a)
{
double ar;
Console.WriteLine( "Radius of the circle: " + a);
ar = 3.14 * a * a;
Console.WriteLine( "Area of circle: " + ar);
static void circumference()
{
double cr;
cr = 2 * 3.14 * a;
Console.WriteLine( "Circumference of the circle is: " + cr);
}
}
AreaofCircle(30);
}
}
|
Output:
Error CS8421: A static local function cannot contain a reference to 'a'. (CS8421) (f)