Today we will learn a cool feature called Local Functions in our newly upgraded version of C#; i.e., 7.0.
As we already know about Public and Private functions in our C# language, what exactly are these local functions? And how it is helpful? When should we use this feature?
Just recall what public and private functions are before digging into local functions.
- Public Functions are accessible everywhere wherever a respective class is accessed.
- Private Functions are accessible only at class level functions and cannot be visible or accessible to the outer world.
Now, it’s time to know more about Local Functions. Local Functions are used within the given function/method.
Where we can use these Local Functions?
Functions/Methods which contain a repeated set of statements need to execute but the scope of this functionality is set to this parent function.
For example, let’s take a simple example of a calculator. Suppose we have a method called calculate with input as a string like [1+(2*5)/10]. Here in this string you might expect many additions, multiplications, and divisions.
As we know all these calculations are used only in this Calculate () method and not used at any part of the class. You can make these as other private functions and use these functions in the Calculate method. However, here we need to consider two points:
- These methods are useful nowhere except in our Calculate method.
- Unnecessarily overloading the stack with these method calls.
Local Functions will overcome these issues, as when we call Local Functions CLR won’t push any method call to the calling task, as this is part of the parent method itself.
Following is the example program which presents what we discussed above.
- public static string Calculate(string expression)
- {
- string result = string.Empty;
-
-
-
- T Addition < T > (T a, T b) {
- return (a + b);
- }
- T Substration < T > (T a, T b) {
- return (a - b);
- }
- T Multiplication < T > (T a, T b) {
- return (a * b);
- }
- return result;
- }
Advantages
- The scope of these functions is limited to their parent method.
- No overhead of adding additional stack push for these method calls, as these calls are part of parent call.
- Can use generic functions.
Note
We can even achieve similar functionality in older versions of C# via. Func and Action but here we have some disadvantages, such as more memory utilization and it will not allow using generics.
I hope you got some help in understanding this article about Local Functions. Please do not forget to leave a comment, which makes me more energetic to provide things here.
Happy Coding.