Gendarme.Rules.Performance.AvoidRepetitiveCastsRule Class
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.

See Also: AvoidRepetitiveCastsRule Members

Syntax

[Gendarme.Framework.EngineDependency(typeof(Gendarme.Framework.Engines.OpCodeEngine, Gendarme.Framework, Version=2.8.0.0, Culture=neutral, PublicKeyToken=null))]
[Gendarme.Framework.FxCopCompatibility("Microsoft.Performance", "CA1800:DoNotCastUnnecessarily")]
[Gendarme.Framework.Problem("The method seems to repeat the same cast operation multiple times.")]
[Gendarme.Framework.Solution("Change the logic to ensure the (somewhat expensive) cast is done once.")]
public class AvoidRepetitiveCastsRule : Gendarme.Framework.Rule, Gendarme.Framework.IMethodRule

Remarks

This rule is available since Gendarme 2.0

Example

Bad example:

Example

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

Example

Good example:

Example

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

Example

Bad example:

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);
            	}
            

Example

Good example:

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);
            	}
            

Requirements

Namespace: Gendarme.Rules.Performance
Assembly: Gendarme.Rules.Performance (in Gendarme.Rules.Performance.dll)
Assembly Versions: 2.8.0.0