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);
}];
}
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.
void fooWithBlock(Action<int> block)
{
int a = 5;
block(a);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With