I don't know if this is possible in C#. But here's what I'm trying to do: An interface that declares a method with a completion block / callback / lambda / whatever you want to call it. Seems simple enough. But, here's a first attempt:
namespace N {
interface MyInterface {
delegate void CompletionBlock();
void doSomething(CompletionBlock completionBlock);
}
}
But interfaces can't declare delegates. Ok, how about this?
namespace N {
public delegate void CompletionBlock();
interface MyInterface {
void doSomething(CompletionBlock completionBlock);
}
}
Sure that works, but now, say I declare another type of CompletionBlock, one which takes an argument for instance. I can't call the type CompletionBlock because it'll clash with the above type, if inside the same namespace.
Then there's Action and Func. But even Action takes a parameter, and I want no parameters. So Action doesn't seem like a viable candidate. Really, all I want, is a way of inlining the concept of "anonymous block as long as the signature is void(void). Something like this:
namespace N {
interface MyInterface {
void doSomething(typeof(()=>) completionBlock);
}
}
But lambdas don't really have a type in C#. Do they at least have signatures? Basically, is there any way around this?
In Objective-C, for instance, blocks are of type NSBlock, even though their signatures themselves are not easily accessible, but one can create a method that takes a block with a specific signature. For instance:
- (void)doSomething:(void(^)(void))completionBlock
Would be a method that takes a block with no parameters and no return type, and you'd call the method like so, for instance:
[obj doSomething:^(){your block code}];
Then there's Action and Func. But even Action takes a parameter, and I want no parameters. So Action doesn't seem like a viable candidate.
If you use Action (not Action<T>), it does not take parameters.
namespace N {
interface MyInterface {
void doSomething(Action completionBlock);
}
}
This allows you to write:
yourInstance.doSomething(() => DoWhatever(foo));
Or, if DoWhatever is void DoWhatever(), just:
yourInstance.doSomething(DoWhatever);
Use Action<T> or Func<TResult> or one of their siblings or just Action in your case.
Action<...> don't return anything where as Func<..., TResult> do.
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