0

Ignoring the irrelevant parts - I have a requirement to use a delegate with no arguments and no return value, but get a value from it. The current solution is to use a lambda expression and a variable that's declared before it.

string result;
RequiredMethod(() => { result = "the result"; });// Gets the result from a 2nd thread.
//use result

Is there a way to do this without using a lambda expression? I expect there should be, but can't come up with it.

ispiro
  • 26,556
  • 38
  • 136
  • 291
  • Have a look at this http://stackoverflow.com/questions/2448010/how-to-declare-a-generic-delegate-with-an-out-parameter – Søren Lorentzen Dec 01 '15 at 11:57
  • 1
    @PHeiberg He tries to use an `Action` without a lambda that changes the surrounding context. `Func` will not work because it returns the value. The task is to do it without returning it and without lambda. – Sebastian Schumann Dec 01 '15 at 12:02
  • Why are you looking for another way? Is there some problem with your current implementation? – Luaan Dec 01 '15 at 12:21
  • @Luaan This is just an example. The actual code is longer and its readability suffers from its lambdaness. – ispiro Dec 01 '15 at 12:39

2 Answers2

3

Yes of course there is:

public class ValueHolder
{
    public string Value { get; private set; }

    public void AssignValue()
    {
        this.Value = "the result";
    }
}

// usage
var vh = new ValueHolder();
RequiredMethod(vh.AssignValue);

// access value
vh.Value

The code you provided told me that you try to access values from another thread. Please keep in mind that you should not access vh.Value until AssignValue has been called. You need to add some other code to sync these operations (but your lambda has exactly the same problem).

Sebastian Schumann
  • 3,204
  • 19
  • 37
  • 1
    Of course, in the end, the lambda does the exact same thing - it just autogenerates that helper class for you. – Luaan Dec 01 '15 at 12:20
  • @Luaan Yes you're right. But I don't know why a lambda is slower than this solution even if the autogenerated code should look very similar. But that's another topic, we don't discuss that here. – Sebastian Schumann Dec 01 '15 at 12:23
  • Perfect and simple. That's exactly what I was trying to do. (And, yes, the threading has to be done carefully anyway.) – ispiro Dec 01 '15 at 12:36
0

also the question is why do you have to use a delegate. If it's about getting the value you could even implement it in a way like this

string someString;
RequiredMethod(ref someString);

Of course this would change the signature of the RequiredMethod (and the question becomes why you couldn't return a value in the first place.).

You could even write an overload of the 2nd using your lamdba expression.

void RequireMethod(string ref variable) { 
     RequireMethod(() => { variable = "the result";});
}
Batavia
  • 2,497
  • 14
  • 16