Click to Rate and Give Feedback
MSDN
MSDN Library
Visual Studio 2005
 Do not cast unnecessarily
Collapse All/Expand All Collapse All
This page is specific to
Microsoft Visual Studio 2005/.NET Framework 2.0

Other versions are also available for the following:
Visual Studio Team System
Do not cast unnecessarily

TypeName

DoNotCastUnnecessarily

CheckId

CA1800

Category

Microsoft.Performance

Breaking Change

NonBreaking

A method performs duplicate casts on one of its arguments or local variables. For complete analysis by this rule, the tested assembly must be built with debugging information and the associated program database (.pdb) file must be available.

Duplicate casts degrade performance, especially when the casts are performed in compact iteration statements. For explicit duplicate cast operations, store the result of the cast in a local variable and use the local variable instead of the duplicate cast operations.

If the C# is operator is used to test whether the cast will succeed before the actual cast is performed, consider testing the result of the as operator instead. This provides the same functionality without the implicit cast operation performed by the is operator.

To fix a violation of this rule, modify the method implementation to minimize the number of cast operations.

It is safe to exclude a warning from this rule, or ignore the rule entirely, if performance is not a concern.

The following example shows a method that violates the rule using the C# is operator. A second method satisfies the rule by replacing the is operator with a test against the result of the as operator, which decreases the number of cast operations per iteration from two to one.

C#
using System;
using System.Collections;
using System.Windows.Forms;

namespace PerformanceLibrary
{
   public sealed class SomeClass
   {
      private SomeClass() {}

      // This method violates the rule.
      public static void UnderPerforming(ArrayList list)
      {
         foreach(object obj in list) 
         {
            // The 'is' statement performs a cast operation.
            if(obj is Control) 
            {
               // The 'as' statement performs a duplicate cast operation.
               Control aControl = obj as Control;
               // Use aControl.
            }

         }
      }

      // This method satisfies the rule.
      public static void BetterPerforming(ArrayList list)
      {
         foreach(object obj in list) 
         {
            Control aControl = obj as Control;
            if(aControl != null) 
            {
               // Use aControl.
            }
         }
      }
   }
}

The following example shows a method, start_Click, with multiple duplicate explicit casts, which violates the rule, and a method, reset_Click, which satisfies the rule by storing the cast in a local variable.

Visual Basic
Imports System
Imports System.Drawing
Imports System.Windows.Forms

Namespace PerformanceLibrary

   Public Class SomeForm : Inherits Form

      Dim start, reset As Button

      Sub New()

         start = New Button()
         reset = New Button()
         AddHandler start.Click, AddressOf start_Click
         AddHandler reset.Click, AddressOf reset_Click
         Controls.Add(start)
         Controls.Add(reset)

      End Sub

      ' This method violates the rule.
      Private Sub start_Click(sender As Object, e As EventArgs)
      
         Dim controlSize As Size = DirectCast(sender, Control).Size
         Dim rightToLeftValue As RightToLeft = _ 
            DirectCast(sender, Control).RightToLeft
         Dim parent As Control = DirectCast(sender, Control)

      End Sub

      ' This method satisfies the rule.
      Private Sub reset_Click(sender As Object, e As EventArgs)
      
         Dim someControl As Control = DirectCast(sender, Control)
         Dim controlSize As Size = someControl.Size
         Dim rightToLeftValue As RightToLeft = someControl.RightToLeft
         Dim parent As Control = someControl

      End Sub

   End Class

End Namespace
C#
using System;
using System.Drawing;
using System.Windows.Forms;

namespace PerformanceLibrary
{
   public class SomeForm : Form
   {
      Button start, reset;

      public SomeForm()
      {
         start = new Button();
         reset = new Button();
         start.Click += new EventHandler(start_Click);
         reset.Click += new EventHandler(reset_Click);
         Controls.Add(start);
         Controls.Add(reset);
      }

      // This method violates the rule.
      void start_Click(object sender, EventArgs e)
      {
         Size controlSize = ((Control)sender).Size;
         RightToLeft rightToLeftValue = ((Control)sender).RightToLeft;
         Control parent = (Control)sender;
      }

      // This method satisfies the rule.
      void reset_Click(object sender, EventArgs e)
      {
         Control someControl = (Control)sender;
         Size controlSize = someControl.Size;
         RightToLeft rightToLeftValue = someControl.RightToLeft;
         Control parent = someControl;
      }
   }
}
Tags What's this?: Add a tag
Community Content   What is Community Content?
Add new content RSS  Annotations
VB.NET 1.1      David A Nelson   |   Edit   |   Show History
How can violations of this rule be fixed in VB.NET 1.1, when TryCast is not available?
Tags What's this?: Add a tag
Flag as ContentBug
False positive      kwolk ... David M. Kean   |   Edit   |   Show History

This rule is not path aware and therefore does fire known false positives in certain situations.

The following example will fire this rule, however, it is considered a false positive and the warning can be suppressed.

[C#]
 
using System;
 
namespace PerformanceLibrary
{
    public class Class1
    {
        public string ToLowerOrUpper(object value, bool lower)
        {
            if (value == null)
                return null;
 
            if (lower)
            {
                return ((string)value).ToLowerInvariant();
            }
          
            return ((string)value).ToUpperInvariant();
        }
    }
}
Tags What's this?: Add a tag
Flag as ContentBug
Processing
© 2012 Microsoft. All rights reserved. Terms of Use | Trademarks | Privacy Statement
Page view tracker