Is ReSharper wrong in giving "Access to modified closure" warning?

I have the following code:

static void Main(string[] args)
        {
            IList<Func<int>> funcs = new List<Func<int>>();

            for (int i = 0; i < 5; i++)
            {
                int i1 = i;
                int k = -1;
                for (int j = 0; j < 3; j++)
                {
                    funcs.Add(() =>
                                  {
                                      int localK = Interlocked.Increment(ref k);
                                      Console.WriteLine("(i, k)=({0}, {1})", i1, localK);
                                      return 0;
                                  });
                }
            }

            foreach (var func in funcs)
            {
                func();
            }
        }

ReSharper shows "Access to modified closure" for k in this line:

int localK = Interlocked.Increment(ref k);

However I get correct result (I also get the same result when I apply the resharper suggested fix):
(i, k)=(0, 0)
(i, k)=(0, 1)
(i, k)=(0, 2)
(i, k)=(1, 0)
(i, k)=(1, 1)
(i, k)=(1, 2)
(i, k)=(2, 0)
(i, k)=(2, 1)
(i, k)=(2, 2)
(i, k)=(3, 0)
(i, k)=(3, 1)
(i, k)=(3, 2)
(i, k)=(4, 0)
(i, k)=(4, 1)
(i, k)=(4, 2)

Is Resharper wrong?

I'm using Resharper 6.1.37.86 with VS 2010, .Net 4.0.

0
3 comments
Avatar
Andrey Serebryansky

Hello Ivan
     This looks like a bug to me. I've logged it under http://youtrack.jetbrains.com/issue/RSRP-318413 and you're welcome to monitor the request's status. Thank you!

Andrey Serebryansky

Senior Support Engineer

JetBrains, Inc

http://www.jetbrains.com

"Develop with pleasure!"

0

No change in status for eight months?


0

Hi Rennie,

I've updated the request status.

Thank you.

0

Please sign in to leave a comment.