Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does adding to a method group count as using a variable?

Tags:

c#

resharper

I have the following code example taken from the code of a Form:

    protected void SomeMethod()
    {
        SomeOtherMethod(this.OnPaint);
    }

    private void SomeOtherMethod(Action<PaintEventArgs> onPaint)
    {
        onPaint += MyPaint;
    }

    protected void MyPaint(PaintEventArgs e)
    {
        // paint some stuff
    }

The second method (SomeOtherMethod) has resharper complaining at me. It says of onPaint that "Value assigned is not used in any execution path".

To my mind it was used because I added a method to the list of methods called when a paint was done.

But usually when resharper tells me something like this it is because I am not understanding some part of C#. Like maybe when the param goes out of goes out of scope the item I added to the list gets removed (or something like that).

I thought I would ask here to see if any one knows what resharper is trying to tell me.

(Side Note: I usually just override OnPaint. But I am trying to get OnPaint to call a method in another class. I don't want to expose that method publicly so I thought I would pass in the OnPaint group and add to it.)

like image 433
Vaccano Avatar asked Feb 14 '11 22:02

Vaccano


2 Answers

The warning is correct. Consider the following:

int X;
int Y;
void SomeMethod()
{         
    SomeOtherMethod(this.X);
}      
void SomeOtherMethod(int x)
{
    x += this.Y;
}

Here the code modifies formal parameter x, and then never uses the modified x. This does not modify "this.X"

You've done the same thing with the delegate. You modify the formal parameter and then never use the result; the original "OnPaint" is unchanged, just as "X" is unchanged in my example.

Remember, just because a delegate is a reference type does not mean that you're passing around a reference to a variable when you pass around an instance. You're passing a reference to an instance, not a reference to the storage location of that instance.

like image 61
Eric Lippert Avatar answered Nov 14 '22 23:11

Eric Lippert


Delegates are immutable. You can't change them. They're a bit like strings in that respect. Imagine your method was:

private void SomeOtherMethod(string x)
{
    x += "hello";
}

Again, that would be a pointless method. The original string wouldn't have changed - you'd just have changed the value of the local variable (the parameter) to refer to a different string. The exact same thing happens in your delegate case.

Either you need to pass the variable by reference or you need to change your whole design.

See my article on delegates and events for more about how delegate combining works.

like image 28
Jon Skeet Avatar answered Nov 14 '22 23:11

Jon Skeet