In C# 6.0 there is no way to declare a function which is local to another function, that is a function visible only inside the body in which is declared. The best way to accomplish this is to declare a delegate variable of type Func<T1,TResult> (or one of the several overloads available), ad then use anonymous methods or lambda expression to write the code of the function, as shown here.
// c# 6.0
Func<int, int, int> sum = (k, y) => {
return k + y;
};
int c = sum(a, b);
This is not an optimal way to use local function, because of some limitations.
C# 7.0 comes with a true local function, and overcomes all the previous limitations.
Here is an example:
int DoSum(int a, int b)
{
return LocalSum(a, b);
int LocalSum(int x, int y)
{
return x + y;
}
}
This is a more natural way to declare and use a local function.
712 thoughts on “C# 7.0 – #4. Local functions”
Comments are closed.