Down-Casting
C#
2
Posts
2
Posters
0
Views
1
Watching
-
Hi all, Is it possible to do down-casting? If so, how? Example: Public class A { } Public class B : A { } Void main() { A a = new A(); B b = (B)a; // <-- down-cast, a run time error. :confused: } Thanks in advance.
-
Hi all, Is it possible to do down-casting? If so, how? Example: Public class A { } Public class B : A { } Void main() { A a = new A(); B b = (B)a; // <-- down-cast, a run time error. :confused: } Thanks in advance.
No you can not: it would require an existing object (a) to suddenly become larger (in case B has more data members, more methods, than A); this is impossible. The one time "downcasting" is allowed is when reducing the capabilities, as in int i=1234567; short s=(short)i; :)
Luc Pattyn [My Articles] [Forum Guidelines]