0

I'm attempting to see if I can make the following code work with non null-able types. I recently discovered that value types act "strangely" when used as ref parameters - they can be null..

sorry about the screenshot - the code is on a secure VM

Is it possible to return an "assignment target" from a function such that the scenario described by the following code may be realized?

void Main()
{
    // want to call F and assign the result to _result
    CallAndAssign(() => F(), () => _result);
}

int F()
{
    return 1;
}

int _result;

void CallAndAssign<T>(Func<T> functionToCall, Func<T> memberToAssignResultTo)
{
    // As I suspected, this did not work, "left-hand side of an assignment must be a variable, property or indexer" 
    //memberToAssignResultTo() = functionToCall();
}

I realize I could do this by making the second parameter an Action and simply perform the assignment, but that's not really different than doing the same thing on the next line of code.

My intuition is that, if this is possible, then it will involve the use of Expression, one of the last C# topics I've yet to wrap my brain around to a useful degree.

Aaron Anodide
  • 16,906
  • 15
  • 62
  • 121
  • 4
    Why do you want it? Can you provide some code of what you want to simplify/avoid with it? I don't see the problem of doing `_result = F();`.. – Ortiga Aug 13 '15 at 22:33
  • You are right, you would have to use `Expression> memberToAssignResultTo` to be able to break the lambda down and then use reflection to update the property. As an `Func` you can't. – Enigmativity Aug 13 '15 at 22:36
  • Look into this question: http://stackoverflow.com/questions/6339602/why-doesnt-c-sharp-support-the-return-of-references – Den Aug 13 '15 at 22:43
  • Looks like "I'm off to see the Lippert...." :) – Aaron Anodide Aug 13 '15 at 22:44
  • 1
    Please don't post code as images. – Sam Axe Aug 14 '15 at 00:22
  • yeah I know, it was on a secured VM (obviously the code is generic enough that I didn't worry).. just being lazy – Aaron Anodide Aug 14 '15 at 01:11

0 Answers0