2

I have a part of code which is repeated multiple time in a function. However I'd like to make a function of it, but I'd like it to know the variables of my function so it can modify them without the need to pass them (because there is a lot).

example of what I want to accomplish

static void Main(string[] args)
{
  int x = 0

  subfunction bob()
  {
    x += 2;
  }

  bob();
  x += 1;
  bob();
  // x would equal 5 here
}
Cher
  • 2,789
  • 10
  • 37
  • 64

3 Answers3

7

Use Action:

static void Main(string[] args)
{
      int x = 0;
      Action act = ()=> {
        x +=2;
      };


      act();
      x += 1;
      act();
      // x would equal 5 here
      Console.WriteLine(x);
}
Cher
  • 2,789
  • 10
  • 37
  • 64
vmg
  • 9,920
  • 13
  • 61
  • 90
2

You could wrap your parameters into a class.

public class MyParams
{
    public int X { get; set; }
}

public static void bob(MyParams p)
{
    p.X += 2;
}

static void Main()
{
    MyParams p = new MyParams { X = 0 };
    bob(p);
    p.X += 1;
    bob(p);
    Console.WriteLine(p.X);
}

This is roughly what the lambda answers are doing behind the scenes.

juharr
  • 31,741
  • 4
  • 58
  • 93
1

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
Community
  • 1
  • 1
Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555