3

Let's say I have this method:

public static object CallMethod(Delegate method, params object[] args)
{
    //more logic
    return method.DynamicInvoke(args);
}

This below has worked fine for most scenarios, calling it like so (simple example):

Delegate methodCall = new Func<decimal,decimal>(Math.Ceiling);
object callResult = CallMethod(methodCall, myNumber);

However, I've run into a situation where I need to use this on a method that takes in a 'ref' parameter (WCF service call), which the Func class can not handle.

Delegate methodCall =
    new Func<MyService.InputClass, MyService.CallResult>(service.DoWork);

Since I don't have a lot of experience dealing with delegates, what would be the easiest way of creating a delegate for the above method to pass on to mine?

John Saunders
  • 160,644
  • 26
  • 247
  • 397
John
  • 17,163
  • 16
  • 65
  • 83
  • Rewrite the method so it doesn't have a `ref` parameter? – dtb Jan 19 '12 at 18:08
  • @dtb - I'm hoping there's an easier way than wrapping the service generated wrapper in a custom function to resolve the problem – John Jan 19 '12 at 18:13
  • See http://stackoverflow.com/questions/5197965/c-sharp-funct-not-accepting-ref-type-input-parameter for why ref isn't allowed and see http://stackoverflow.com/questions/1283127/c-sharp-func-with-out-parameter for a possible solution. – dash Jan 19 '12 at 18:13
  • I really can't see any feasible way of achieving this, maintaining the "ref" in the method signature AND using your CallMethod method. In general, any "ref" values would be rendered moot anyways as you are not able to pass back the ref'd value from the CallMethod method. – doogle Jan 19 '12 at 18:18
  • Or declare a custom delegate type. You may get surprising results if you're calling it dynamically with a `params` array, though. (it will change the value _in the array_, but not in the place you called it from) – Random832 Jan 19 '12 at 18:19

1 Answers1

0

This isn't my application so I don't have an easy way of testing it (I was just asked if I knew of a way of resolving the problem), but does this look like it should work?

Delegate methodCall = new Func<MyService.CallResult>(delegate() { return service.DoWork(ref myInput)});
object callResult = CallMethod(methodCall, null);
John
  • 17,163
  • 16
  • 65
  • 83
  • why doesn't the person owning the application ask the question here? – Adam Ralph Jan 19 '12 at 19:16
  • @AdamRalph - He has not been enlightened to the ways of StackOverflow. On a side note I received an email back saying this did work; there were no problems with the ref variable either (it was correctly updated) – John Jan 19 '12 at 19:31
  • Good to hear. As for SO, perhaps you should enlighten him ;-) – Adam Ralph Jan 19 '12 at 20:48