Function within a method in C# / csharp / dotnet
I have since the birth of dotnet missed the possibility to have a function inside a function like one can in Pascal.
With lambda, and possibly Dotnet4(?) it is possible. Below is a rather stupid example.
1 2 3 4 5 6 7 8 | internal int AddMaxWierd( int x, int y ) { Func Max = delegate( int a ){ return Math.Min( a, 10 ); }; return Max(x) + Max(y); } |
If the inner method doesn’t have a return value, use “Action” instead of “Func”.
See how there is only one Manipulate method in the class, the other Manipulate method is hidden within the method.
1 2 3 4 5 6 7 8 9 10 11 12 | internal void Manipulate( CustomerList Customer customers ) { Action<Customer> Manipulate = delegate( Customer customer ) { // do stuff... }; foreach( var customer in customers ){ Manipulate( customer ); } } |
Update:
In C#7 it can be done. https://github.com/dotnet/roslyn/issues/6505