Why is this an issue?

A cast is an explicit conversion, which is a way to tell the compiler the intent to convert from one type to another.

In Visual Basic, there are two explicit conversion operators:

Public Sub Method(Value As Object)
    Dim i As Integer
    i = DirectCast(Value, Integer)  ' Direct casting from object holding an integer type to Integer
    i = CType(Value, Integer)       ' Conversion from the underlying type to Integer
End Sub

In most cases, the compiler will be able to catch invalid casts between incompatible value types or reference types.

However, the compiler will not be able to detect invalid casts to interfaces.

What is the potential impact?

Invalid casts will lead to unexpected behaviors or runtime errors such as InvalidCastException.

Exceptions

No issue is reported if the interface has no implementing class in the assembly.

How to fix it

To prevent an InvalidCastException from raising during an explicit conversion, it is recommended to use the TryCast operator. When the conversion is not possible, the TryCast operator returns Nothing and will never raise an exception.

Code examples

Noncompliant code example

Public Interface IMyInterface
End Interface

Public Class Implementer
    Implements IMyInterface
End Class

Public Class AnotherClass
End Class

Module Program
    Sub Main()
        Dim Another As New AnotherClass
        Dim x As IMyInterface = DirectCast(Another, IMyInterface)   ' Noncompliant: InvalidCastException is being thrown
    End Sub
End Module

Compliant solution

Public Interface IMyInterface
End Interface

Public Class Implementer
    Implements IMyInterface
End Class

Public Class AnotherClass
End Class

Module Program
    Sub Main()
        Dim Another As New AnotherClass
        Dim x = TryCast(Another, IMyInterface)                      ' Compliant: but will always be Nothing
    End Sub
End Module

Resources

Documentation