You can do this by using a lambda expression:
public static void SomeMethod () {
int x = 0;
Action bob = () => {x += 2;};
bob();
x += 1;
bob();
Console.WriteLine(x); //print (will be 5)
}
The lambda expression is the following part() => {x += 2;}
. The ()
denotes that the action takes no input at all. Between accolades, you can then specify the statements that should be executed. Variables not defined on the left of the lambda expression (llike x
) are bounded like the normal rules of scoping in the C/C++/Java language family. Here x
thus binds with the local variable x
in SomeMethod
.
Action
is a delegate
, it refers to a "method", and you can call it as a higher-order method.
Note that your code is not C#. You cannot write int main
as main method.
Demo (Mono's C# interactive shell csharp
)
$ csharp
Mono C# Shell, type "help;" for help
Enter statements below.
csharp> public static class Foo {
>
> public static void SomeMethod () {
> int x = 0;
> Action bob = () => {x += 2;};
> bob();
> x += 1;
> bob();
> Console.WriteLine(x);
> }
>
> }
csharp> Foo.SomeMethod();
5