## 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.

    void Method(object value)
    {
        int i;
        i = (int)value;   // Casting (explicit conversion) from float to int
    }

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 `as` operator. When the conversion is not possible, the `as` operator returns `null` and will never raise an exception.

### Code examples

#### Noncompliant code example

    public interface IMyInterface
    { /* ... */ }

    public class Implementer : IMyInterface
    { /* ... */ }

    public class AnotherClass
    { /* ... */ }

    public static class Program
    {
      public static void Main()
      {
        var another = new AnotherClass();
        var x = (IMyInterface)another;     // Noncompliant: InvalidCastException is being thrown
      }
    }

#### Compliant solution

    public interface IMyInterface
    { /* ... */ }

    public class Implementer : IMyInterface
    { /* ... */ }

    public class AnotherClass
    { /* ... */ }

    public static class Program
    {
      public static void Main()
      {
        var another = new AnotherClass();
        var x = another as IMyInterface;    // Compliant: but will always be null
      }
    }

## Resources

### Documentation

- Casting and type conversions - Explicit conversion
- Type-testing operators and cast expressions
  - `is` operator
  - `as` operator
- Conversions - Explicit conversions in C#
  - Conversions - Explicit reference conversions in C#
- CWE - CWE-588 - Attempt to Access Child of a Non-structure Pointer
- CWE - CWE-704 - Incorrect Type Conversion or Cast