Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling a method with ref or out parameters from an anonymous method [duplicate]

Tags:

c#

.net

This question is related to one I asked the other day which I got some good helpful answers from.

I needed to call various web methods with varying signatures in a generic way. I wanted to be able to pass the web method to a method which had a delegate argument but I was unsure how to deal with the varying signatures. The solution was to use lambdas (or anonymous methods as I'm using C#2 at the moment).

This worked nicely until I needed my anonymous method to call a web method with out parameters. You can't do this for reasons explained here.

So my question is, other than creating a wrapper method with no ref or out params to call from my anonymous method, is there a easier way to accomplish this?

like image 535
Charlie Avatar asked Jun 16 '09 13:06

Charlie


1 Answers

Actually, you can use ref and out - just not directly with the calling method's parameters; you can, however, just copy the values before and after invoking:

static void Foo(ref string s, out int i)
{
    string tmpS = s;
    int tmpI = 0; // for definite assignment
    DoIt(delegate { Bar(ref tmpS, out tmpI); });
    s = tmpS;
    i = tmpI;
}
like image 157
Marc Gravell Avatar answered Nov 10 '22 00:11

Marc Gravell