What exactly is the Outer Variable Trap?
Explanation and examples in C# are appreciated.
EDIT: Incorporating Jon Skeet’s diktat 🙂
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
The "Outer Variable Trap" occurs when a developer expects the value of a variable to be captured by a lambda expression or anonymous delegate, when actually the variable is captured itself.
Example:
Possible output #1:
Possible output #2:
If you expected output #1, you’ve fallen into the Outer Variable Trap. You get output #2.
Fix:
Declare an "Inner Variable" to be captured repeatedly instead of the "Outer Variable" which is captured only once.
For more details, see also Eric Lippert’s blog.