Skip to content

Gendarme.Rules.Performance.AvoidRepetitiveCastsRule(2.10)

Sebastien Pouliot edited this page Jan 22, 2011 · 2 revisions

AvoidRepetitiveCastsRule

Assembly: Gendarme.Rules.Performance
Version: 2.10

Description

This rule fires if multiple casts are done on the same value, for the same type. Casts are expensive so reducing them, by changing the logic or caching the result, can help performance.

Examples

Bad example:

foreach (object o in list) {
    // first cast (is)
    if (o is ICollection) {
        // second cast (as) if item implements ICollection
        Process (o as ICollection);
    }
}

Good example:

foreach (object o in list) {
    // a single cast (as) per item
    ICollection c = (o as ICollection);
    if (c != null) {
        SingleCast (c);
    }
}

Bad example:

// first cast (is):
if (o is IDictionary) {
    // second cast if item implements IDictionary:
    Process ((IDictionary) o);
    // first cast (is):
    } else if (o is ICollection) {
        // second cast if item implements ICollection:
        Process ((ICollection) o);
    }
    

Good example:

// a single cast (as) per item
IDictionary dict;
ICollection col;
if ((dict = o as IDictionary) != null) {
    SingleCast (dict);
    } else if ((col = o as ICollection) != null) {
        SingleCast (col);
    }
    

Notes

  • This rule is available since Gendarme 2.0
Clone this wiki locally