What are Local Functions in C# 7.0?
The local function is an ability to declare methods inside an already defined function’s body. We are able to write local functions in C# 6.0 too but they can’t have a complete body or function name, and can only be anonymous.
Why Local Functions in C# 7.0?
As per the Microsoft blog, this is already (kind of) possible by using the Func and Action types with anonymous methods.
However, they lack a few features,
- Generics
- ref and out parameters
- params
How to write Local Functions in C# 7.0
Local functions have the same capabilities as normal methods but will only be scoped to the block they were declared in.
Now, let’s try to write a normal local function first.
In the following image of code, you can check that I just created a function with two argument types (int, string) and it has all the behavior as a normal function. Since it is a local function, you can use or call it within the same function only.
Code
- static void Main(string[] args)
- {
- string myFunc(int p1,string p2)
- {
- return p2.Substring(p1);
- }
-
- Console.WriteLine(myFunc(2,"Nitin Pandit"));
- Console.Read();
- }
We can also use other properties of local function, like Generics, ref/out parameters, and params. So, let’s see how to use them.
- Local Generics Functions
Local Generic function is really a nice property. It can be used in the same way as in a normal function and we can call it within the root function. In the following example, I have created myFunc as Generic.
Code
- static void Main(string[] args)
- {
- void myFunc<T>(T value)
- {
- Console.WriteLine(value);
- }
-
-
- myFunc<string>("Nitin Pandit");
- Console.Read();
- }
- Using out/ref in Local Functions
Code
- static void Main(string[] args)
- {
- void myFunc(int value1, out int value2)
- {
- value2 = value1 + value1;
- Console.WriteLine();
- }
- int i = 0;
- myFunc(12, out i);
- Console.WriteLine($"New Value of i : {i}");
- Console.Read();
- }
- Using params in Local Functions
Code
- static void Main(string[] args)
- {
- void myFunc(params int[] items)
- {
- int res = 0;
- foreach (var item in items)
- {
- res += item;
- }
- Console.WriteLine($"Total : {res}");
- }
-
- myFunc(1,2,3,4,5,6,7,8,9);
-
- Console.Read();
- }
All these properties of local function make C# 7.0 more powerful. Thanks for reading this article. Stay tuned with us for more updates:
Connect (“Nitin Pandit”);