Home > Enterprise >  Invalid Cast Exception but build works fine
Invalid Cast Exception but build works fine

Time:09-27

public class A
    {
        public void M1()
        {
            Console.Write("Print M1 of Class A");
        }
    }
public class B:A
{
    public void M2()
    {
        Console.Write("Print M2 of Class B");
    }
}

public class C : B
{
    public void M3()
    {
        Console.Write("Print M3 of Class C");

    }
}

In main method we create objects like:-

   A objA = new B();
    B objB = new C();
    A a = new A();
    C objC = (C)a;  /* this line throws runtime error System.InvalidCastException: 'Unable to cast object of type 'A' to type 'C'.'  but build works fine */

        objA.M1();
        objB.M1();
        objB.M2();
        objC.M1();
        objC.M2();
        objC.M3();

I could not cast C to A directly first. Hence tried creating object A then explicit casted it. The intellisense takes it as valid code and build is also fine but during console app execution it throws error "Unable to cast object of type 'A' to type 'C'."

CodePudding user response:

It's true; you could cast a C to an A any time you want but the only time you can do it the other way round is if you've stored a C in a variable typed as A. The compiler lets you do this because C descends from A, so a variable of type A is capable of holding an instance of type C. Hence, you could have legitimately stored a C in an A and you're casting to get it back to being a C:

A reallyC = new C();
C gotBack = (C)reallyC;

The compiler doesn't look too hard at what you've done before; it wouldn't see code like this:

A reallyA = new A();
C willFail = (C)reallyA;

and say "hey; you've stored an A in reallyA, and it can't be cast to a C". It just sees you attempt to cast reallyA to a C and thinks "it could be a C, because a C is a B is an A, so they're related ok.. I trust the dev knows what they're doing and I'll permit it"

CodePudding user response:

Well, a is of (base) type A and can't be cast to C since C is derived from A. The reverse is possible: an object c of derived class C can be cast to base class A:

 C c = new C(); 
 A objA = (A) c;

Often we can try to cast with a help of is:

if (a is C objC) {
  // a can be cast to C, objC now holds the result of the cast  
  objC.M3();
}
else {
  // the cast is impossible
}
  •  Tags:  
  • c#
  • Related