CS.WRONG.CAST.MIGHT

This warning is reported in situations when one object can be cast to another object with the possibility of lost data or even program failure.

Vulnerability and risk

Either data may be lost, or the program may fail. This can happen when a program tries to access a nonexistent class field after a cast.

Example

Copy
public class Base {
  public int b;
}
public class Derived : Base {
  public int a;
}
public class ClassCastTests {
  private bool flag;

  public void foo() {
    Derived d;
    Base b = new Base();
    if (flag)
      d = (Derived)b;
  }
}

Object o1 of class Object1 and object o2 of class Object2 are declared on lines 9-10. Then, on line 12, Object2 can be cast to Object1, depending on flag on line 11, which is invalid.

Security training

Application security training materials provided by Secure Code Warrior.