Cher
Cher

Reputation: 2937

how to have a function containing a sub function in C#

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
}

Upvotes: 2

Views: 436

Answers (3)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476584

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

Upvotes: 1

juharr
juharr

Reputation: 32266

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.

Upvotes: 2

vmg
vmg

Reputation: 10566

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);
}

Upvotes: 7

Related Questions