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)

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 with VS 2010, .Net 4.0.

Andrey Serebryansky
Comment actions Permalink

Hello Ivan
     This looks like a bug to me. I've logged it under and you're welcome to monitor the request's status. Thank you!

Andrey Serebryansky

Senior Support Engineer

JetBrains, Inc

"Develop with pleasure!"

Comment actions Permalink

No change in status for eight months?

Comment actions Permalink

Hi Rennie,

I've updated the request status.

Thank you.


Please sign in to leave a comment.