Uploaded image for project: 'Rules Repository'
  1. Rules Repository
  2. RSPEC-3247

Duplicate casts should not be made

    XMLWordPrintable

    Details

    • Type: Code Smell Detection
    • Status: Active
    • Resolution: Unresolved
    • Labels:
    • Message:
      Hide
      Primary: Replace this type-check-and-cast sequence with an "as" and a null check.
      Secondary: Replace this cast
      Show
      Primary: Replace this type-check-and-cast sequence with an "as" and a null check. Secondary: Replace this cast
    • Highlighting:
      • Primary: on the "is" check
      • Secondary: on the following casts
    • Default Severity:
      Minor
    • Impact:
      Low
    • Likelihood:
      Low
    • Default Quality Profiles:
      Sonar way
    • Covered Languages:
      C#
    • Remediation Function:
      Constant/Issue
    • Constant Cost:
      10min
    • Analysis Scope:
      Main Sources, Test Sources
    • FxCop:
      DoNotCastUnnecessarily
    • ReSharper:
      CanBeReplacedWithTryCastAndCheckForNull

      Description

      Because the is operator performs a cast if the object is not null, using is to check type and then casting the same argument to that type, necessarily performs two casts. The same result can be achieved more efficiently with a single cast using as, followed by a null-check.

      Noncompliant Code Example

      if (x is Fruit)  // Noncompliant
      {
        var f = (Fruit)x; // or x as Fruit
        // ...
      }
      

      Compliant Solution

      var f = x as Fruit;
      if (f != null)
      {
        // code
      }
      

        Attachments

          Issue Links

            Activity

              People

              Assignee:
              Unassigned Unassigned
              Reporter:
              ann.campbell.2 Ann Campbell
              Votes:
              0 Vote for this issue
              Watchers:
              2 Start watching this issue

                Dates

                Created:
                Updated: