Skip to content

Gendarme.Rules.Performance.AvoidUnneededUnboxingRule(git)

Sebastien Pouliot edited this page Mar 2, 2011 · 1 revision

AvoidUnneededUnboxingRule

Assembly: Gendarme.Rules.Performance
Version: git

Description

This rule checks methods which unbox the same value type multiple times (i.e. the value is copied from the heap into the stack). Because the copy is relatively expensive, the code should be rewritten to minimize unboxes. For example, using a local variable of the right value type should remove the need for more than one unbox instruction per variable.

Examples

Bad example:

public struct Message {
    private int msg;
    private IntPtr hwnd, lParam, wParam, IntPtr result;
    public override bool Equals (object o)
    {
        bool result = (this.msg == ((Message) o).msg);
        result &= (this.hwnd == ((Message) o).hwnd);
        result &= (this.lParam == ((Message) o).lParam);
        result &= (this.wParam == ((Message) o).wParam);
        result &= (this.result == ((Message) o).result);
        return result;
    }
}

Good example:

public struct Message {
    private int msg;
    private IntPtr hwnd, lParam, wParam, IntPtr result;
    public override bool Equals (object o)
    {
        Message msg = (Message) o;
        bool result = (this.msg == msg.msg);
        result &= (this.hwnd == msg.hwnd);
        result &= (this.lParam == msg.lParam);
        result &= (this.wParam == msg.wParam);
        result &= (this.result == msg.result);
        return result;
    }
}

Notes

  • This rule is available since Gendarme 2.0

Source code

You can browse the latest source code of this rule on github.com

Clone this wiki locally