14

How would I write the equivalent code in C#:

typedef void (^MethodBlock)(int); 

- (void) fooWithBlock:(MethodBlock)block
{
    int a = 5;
    block(a);
}

- (void) regularFoo
{
    [self fooWithBlock:^(int val) 
    {
        NSLog(@"%d", val);
    }];
}
BoltClock
  • 700,868
  • 160
  • 1,392
  • 1,356
user204884
  • 1,745
  • 2
  • 19
  • 27

2 Answers2

16

Something like this:

void Foo(Action<int> m)
{
    int a = 5;
    m(a);
}

void RegularFoo()
{
    Foo(val => // Or: Foo(delegate(int val)
    {
        Console.WriteLine(val);
    });
}

Action<T> is a delegate that takes exactly one argument of a type you specify (in this case, int), that executes without returning anything. Also see the general C# delegate reference.

For a simple case like this, it's pretty straightforward. However, I believe there are some semantic/technical differences between blocks in Objective-C and delegates in C#, which are probably beyond the scope of this question.

BoltClock
  • 700,868
  • 160
  • 1,392
  • 1,356
  • 1
    Just use `System.Action` and the `delegate`'s done for you. – pickypg Apr 28 '11 at 19:20
  • For the second method, just use an anonymous delegate: `delegate(int x) { Console.WriteLine("{0}", x); }` as the parameter. – pickypg Apr 28 '11 at 19:23
  • @pickypg: I originally opted not to use `Action` because it wouldn't really be clear to an Obj-C coder how it works. But I have a better idea, \*improves your edit\* There, a reference should do the trick. Thanks for suggesting, and sorry for rejecting it earlier :) – BoltClock Apr 28 '11 at 19:25
  • @BoltClock No problem on removing it. It wasn't clear if it was wiped out by editing to add the new part of the question's answer, or not. Not offended either way. – pickypg Apr 28 '11 at 19:29
1
void fooWithBlock(Action<int> block)
{
   int a = 5;
   block(a);
}
Dmitry S.
  • 8,373
  • 2
  • 39
  • 49