Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Objective-C code blocks equivalent in C#

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);
    }];
}
like image 456
user204884 Avatar asked Apr 28 '11 19:04

user204884


2 Answers

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.

like image 157
BoltClock Avatar answered Oct 07 '22 01:10

BoltClock


void fooWithBlock(Action<int> block)
{
   int a = 5;
   block(a);
}
like image 23
Dmitry S. Avatar answered Oct 07 '22 00:10

Dmitry S.