Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Faulty rewrite setting variable from outer scope inside foreach loop without reading it #14

Open
sonix1977nl opened this issue Oct 14, 2016 · 0 comments

Comments

@sonix1977nl
Copy link

If you have a loop that sets a variable living outside the scope of the loop without reading the variable, it results in faulty rewritten code. I have produced a minimal sample that demonstrates the problem.

The file "Program.cs" contains this code:

using System;
using System.Linq;

namespace RoslynLinqRewriteError
{
    public static class Program
    {
        public static void Main()
        {
            var values = new int[] { 1, 2, 3 };
            var result = 0;
            foreach (var value in values.Where(x => (x % 2) == 0))
            {
                result = value;
            }
            Console.WriteLine(result);
        }
    }
}

Compile it with this command:

roslyn-linq-rewrite.exe /reference:"C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.6.2\mscorlib.dll" /reference:"C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.6.2\System.Core.dll" /reference:"C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.6.2\System.dll" /out:RoslynLinqRewriteError.exe /target:exe Program.cs

This will result in the following error:

Could not compile rewritten method. Consider applying a [Shaman.Runtime.NoLinqRewrite] attribute.

(18,9): error CS0103: The name 'result' does not exist in the current context

If you change result = value to result = result + value it compiles without problem because the variable is also read inside of the loop.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant