Locia <(E-Mail Removed)> wrote:
> Can I cast from base class to derive class?
You can cast a base class type reference to a derived class type
reference, but at runtime the CLR will check that the object being
referred to as actually an instance of the derived class (or null).
> class A
> {
>
> }
>
> class B:A
> {
>
> }
>
> A a=new A();
>
> B b=(B) a;
>
> I get a cast exception.
> Why?
Because a *isn't* an instance of B.
Consider this code:
object x = new object();
FileStream y = (FileStream) x;
How on earth could the object actually behave like a FileStream? What
file would it be reading?
--
Jon Skeet - <(E-Mail Removed)>
http://www.pobox.com/~skeet Blog:
http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too