Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C#: Function in Function possible?

Tags:

methods

c#

.net

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;     } } 
like image 599
Non Avatar asked May 04 '11 13:05

Non


2 Answers

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(); } 
like image 197
JaredPar Avatar answered Oct 13 '22 06:10

JaredPar


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(); } 
like image 26
jeroenh Avatar answered Oct 13 '22 06:10

jeroenh