FxC2203 : RefererenceLocalStructCorrectlyInClosure

TypeName RefererenceLocalStructCorrectlyInClosure
CheckId FxC2203
Category FxCopContrib.Usage
Breaking Change Non-breaking

Caution

There seem to be a lot of false positives generated. Please disable this rule until I've had time to investigate

Cause

A value type is used in a Closure in a way that may cause unexpected results.

Rule Description

If a struct is referenced in a Closure and is also assigned to after it is passed to the Closure, it will actually be referenced by reference and not by value as many might expect.

How to fix violations

To fix this violation either assign the value to a different local struct variable or use a method signature that allows you to pass in the variable outside of the closure.

When to suppress warnings

When you want to update a local value typed variable from your Closure, you can ignore this rule. In all other cases, you will want to fix this.

Example

You're passing a loop variable in a lambda expression that is used to start a new Task.

Bad Example
public void BadMethod()
{
     for (int i = 0; i < 100; i++)
     {
          Task.Factory.StartNew(_ => SomeMethod(i));
     }
}

Good Example
public void GoodMethod()
{
     for (int i = 0; i < 100; i++)
     {
          Task.Factory.StartNew((x) => SomeMethod(x), i);
     }
}

Or:

public void GoodMethod()
{
     for (int i = 0; i < 100; i++)
     {
          int temp = i;
          Task.Factory.StartNew(_ => SomeMethod(temp));
     }
}

Last edited Jan 23, 2013 at 12:36 PM by jessehouwing, version 2

Comments

No comments yet.