"Access to modified closure" on initial value assignment

Suppose we have a class whose constructor accepts a delegate:

class DelegateConsumer {

    private Action _action;

    public DelegateConsumer(Action action) {

        _action = action;

    }

}

Then we initialize a variable with an instance whose delegate refers to that variable:

DelegateConsumer consumer = null;

consumer = new DelegateConsumer(() => {

    Console.WriteLine("I am in {0}", consumer);

});


On the Console.WriteLine line, ReSharper will warn "Access to modified closure".

I understand that this happens because of the order of operations:

1. consumer is initialized to null
2. a delegate referencing consumer is created and passed to the DelegateConsumer constructor
3. consumer is assigned to the DelegateConsumer

Since consumer is reassigned after the delegate is created, this could lead to the bug where the delegate is referring to a "newer" value than the programmer expected.

However, I think ReSharper should make an exception for the first non-null assignment. Consider how similar this is to the following common pattern:

EventHandler handler = null;

handler = (sender, e) => {

    SomethingHappened -= handler;

};

SomethingHappened += handler;


In this case, ReSharper won't give the warning. Isn't the same thing happening here, though? i.e.:


1. handler is initialized to null
2. a delegate referencing handler is created
3. handler is assigned to the delegate

If you first assign handler to a non-null value, the warning will be shown, which makes sense. I think both cases should have the same behavior.

Please sign in to leave a comment.