Is it possible to declare a method within another method in C#?
For example like that:
void OuterMethod() { int anything = 1; InnerMethod(); // call function void InnerMethod() { int PlitschPlatsch = 2; } }
Update: Local functions where added in version 7 C#.
void OuterMethod() { int foo = 1; InnerMethod(); void InnerMethod() { int bar = 2; foo += bar } }
In previous version C# you have to use action like this:
void OuterMethod() { int anything = 1; Action InnedMethod = () => { int PlitschPlatsch = 2; }; InnedMethod(); }
UPDATE: C#7 added local functions (https://docs.microsoft.com/en-us/dotnet/articles/csharp/csharp-7#local-functions)
void OuterMethod() { int foo = 1; InnerMethod(); void InnerMethod() { int bar = 2; foo += bar } }
In versions of C# before C#7, you can declare a Func
or Action
and obtain something similar:
void OuterMethod() { int foo = 1; Action InnerMethod = () => { int bar = 2; foo += bar; } ; InnerMethod(); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With