Wednesday, February 29, 2012

what causes a InvalidCastException?

when a parent reference refers to a child - then casting to the child works fine

Parent pt ;
pt = c1;
((Child1)pt).message();

When a parent object is instantiated, likewise this will work

Parent pt = new Parent() ;
pt = c1;
((Child1)pt).message();

However a child object set to a parent will not compile
Parent pt = new Parent();
c1 = pt;

and an explicit cast will cause a runtime error  InvalidCastException

Parent pt =
new Parent();

c1 = (Child1)pt;//invalidcast


if however the parent is referencing a child then of course there is no runtime error

Parent
pt = new Parent();

pt = c1;
c1 = (Child1)pt;

No comments:

Post a Comment