Barry McDermid
Barry McDermid

Reputation: 339

How to create generic delegate from a method within an object

I'm Trying to create a generic delegate like this:

Func<string, string, IEnumerable<MyPOCO>> del  = 
WCFServiceInstance.GetLabs(SessionStateService.Var1,SessionStateService.Var2));

but it seems because GetLabs is within a WCFServiceInstace the Func delegate just thinks I'm passing it an IEnumerable rather than

Func<string, string, IEnumerable<MyPOCO>> 

which is what I'm trying to pass it.

Upvotes: 0

Views: 51

Answers (4)

dcastro
dcastro

Reputation: 68660

There's something else wrong with your approach. Are the two arguments supposed to be always SessionStateService.Var1 and SessionStateService.Var2? Or will those be the delegate's arguments?

If you want them to be the delegate's parameters:

Func<string, string, IEnumerable<MyPOCO>> del  =
   WCFServiceInstance.GetLabs;

del(SessionStateService.Var1, SessionStateService.Var2);

If you want the method be invoked with those specific values, use a closure instead:

Func<IEnumerable<MyPOCO>> del  =
   () => WCFServiceInstance.GetLabs(SessionStateService.Var1, SessionStateService.Var2);

del();

Bear in mind that if you use a closure, SessionStateService.Var1 and SessionStateService.Var2 will be evaluated when the delegate is called (line 2), not when it is declared (line 1). So, if you pass this second delegate around and call it later, the values of the arguments might have changed.

If you want to prevent that, you can use eager evaluation, as exemplified by @knittl in the comments:

string var1 = SessionStateService.Var1,
       var2 = SessionStateService.Var2;

Func<IEnumerable<MyPOCO>> del = () => WCFServiceInstance.GetLabs(var1, var2);

Upvotes: 2

Alberto
Alberto

Reputation: 15941

Func<string, string, IEnumerable<MyPOCO>> del = WCFServiceInstance.GetLabs;

and then use it like:

del(SessionStateService.Var1,SessionStateService.Var2);

Upvotes: 1

knittl
knittl

Reputation: 265201

I think you want a lambda expression to partially apply the function, fixing the first two arguments:

Func<IEnumerable<MyPOCO>> del  =
  () => WCFServiceInstance.GetLabs(
    SessionStateService.Var1,
    SessionStateService.Var2);

Call as del().

Upvotes: 0

Baldrick
Baldrick

Reputation: 11840

I think you want:

Func<string, string, IEnumerable<MyPOCO>> del = WCFServiceInstance.GetLabs;

That is, assuming WCFServiceInstance.GetLabs has the following signature:

IEnumerable<MyPOCO> WCFServiceInstance.GetLabs(string, string)

Upvotes: 0

Related Questions