There has been a feature of having a class within a class in C#. It is a very powerful mechanism of C# that you can create classes within a class. Many times it makes sense that you just need a certain type in the boundary of another type implementation. The intent being
- Loosely coupled
- Encapsulated within the class
- Being Limited in scope of the Containing class
Similarly now we are being provided with Local functions, that is a function inside the body of a function and remains in the scope of that function only.
The above code says that a local function Iterator is being created because even if we create a private Iterator function in the class that will be available to other methods of the class as well which we may not want sometimes.
Local functions can be defined in methods and also in the body of Get and Set of a property. The compiler converts this method as a static method to the class. Even though it seems like the same thing can be achieved through delegates Func and Action. But it gives much more performance improvement as compared to delegates where they are allocate space in memory and Local Function being compiled as a static method remains on the class level and shared accross objects.
Show Comments (0)