Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# How to declare lambda or anonymous function type in method argument list?

Tags:

c#

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}];
like image 367
SaldaVonSchwartz Avatar asked Dec 04 '25 02:12

SaldaVonSchwartz


2 Answers

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);
like image 108
Reed Copsey Avatar answered Dec 05 '25 15:12

Reed Copsey


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.

like image 34
Daniel A. White Avatar answered Dec 05 '25 16:12

Daniel A. White



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!