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

"CType" should be used for casting and explicit conversions

    XMLWordPrintable

    Details

    • Type: Code Smell Detection
    • Status: Closed
    • Resolution: Won't Fix
    • Labels:
    • Message:
      Use CType(<expression>, {0}) when casting is intended, or an explicit conversion.
    • Default Severity:
      Major
    • Impact:
      Low
    • Likelihood:
      High
    • Targeted languages:
      VB.Net
    • Irrelevant for Languages:
      ABAP, C#, C, C++, Cobol, CSS, Flex, HTML, Java, JavaScript, Objective-C, PHP, PL/I, PL/SQL, Python, RPG, Swift, VB6, XML
    • Remediation Function:
      Constant/Issue
    • Constant Cost:
      5min
    • Analysis Scope:
      Main Sources, Test Sources

      Description

      For the sake of backward compatibility, Visual Basic .NET continues to offer a set of functions that convert from Object to different primitive types: CChar, CStr, CBool, CDate, CSng, CDbl, CDec, CByte, CSByte, CShort, CUShort, CInt, CUInt, CLng, CULng. However, using these functions is misleading, because it suggests a cast. It is better to cast explicitly using CType(), or use Convert.To() when the value should be converted.

      Noncompliant Code Example

      Public Class Foo
          Public Sub Bar(value as Object)
              Dim stringValue As String = CStr(value)
          End Sub
      End Class
      

      Compliant Solution

      Public Class Foo
          Public Sub Bar(value as Object)
              Dim stringValue As String = CType(value, String)
          End Sub
      End Class
      

        Attachments

          Activity

            People

            Assignee:
            Unassigned Unassigned
            Reporter:
            valeri.hristov Valeri Hristov (Inactive)
            Votes:
            0 Vote for this issue
            Watchers:
            3 Start watching this issue

              Dates

              Created:
              Updated:
              Resolved: