Note that there are some explanatory texts on larger screens.

plurals
  1. POScope of string inside lambda
    text
    copied!<p>I have an interesting scenario in which I've built a validation checking system that maintains a series of requirements in the form <code>List&lt;Tuple&lt;Func&lt;bool&gt;, string&gt;&gt;</code> where the Func should return true if validation failed and false otherwise. The string is a corresponding rejection description that describes the condition should the test fail.</p> <p>In more simple tests like the following the validation system is quite simple:</p> <pre><code>validationChecks.Add(Tuple.Create&lt;Func&lt;bool&gt;, string&gt;(() =&gt; value1 == requiredValue, "value 1 did not have the required value")); </code></pre> <p>I'm struggling to understand the scope of variables within the lambda for the Func in a more advanced scenario in which the rejection string is calculated in a call to another part of the system. The scenario looks something like this:</p> <pre><code>string rejectionString = null; validationChecks.Add(Tuple.Create&lt;Func&lt;bool&gt;, string&gt;(() =&gt; { rejectionString = CallToAnotherMethodThatReturnsString(parameter); if (rejectionString != null) { return true; } else { return false; } }, rejectionString)); </code></pre> <p>EDIT: As observed through testing, when this check fails the rejectionString from the Tuple is still null. I want the rejectionString that was generated by the CallToAnotherMethod to be used instead, is there any way I can do this using ref or otherwise? I need the Func's code to be able to affect the value of the string inside Item2 of the Tuple.</p> <p><strike>The problem is that the code inside of <code>CallToAnotherMethodThatReturnsString</code> might be code that I only want executed ONCE. However should the check fail I want to use the string that would have been returned from it as my rejection description in the Tuple. I'm unable to tell at this point what the effect of my use of <code>rejectionString</code> in this second example will accomplish? Will rejectionString inside the Tuple always be null? Or if <code>CallToAnotherMethodThatReturnsString</code> returns a different value will it be updated?</strike></p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload