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
Hey man,
You could probably use the Emitter to generate a method at run time and execute it, or just use the method info of a method. What exactly is the point here?
Emit takes a string with code IIRC. This means no debug possibilities and no intellisense.
MethodInfo takes a reference to a method that already has to be somewhere.
The solution I presented above makes a function inside another function without any tricks.