Both directions are allowed in Java and C #. Downcasting requires an explicit cast and may throw an exception if the object does not match the correct type. However, to increase the rating there is no explicit actuation and is always safe.
That is, if you have a public interface Animal and two implementations of these interface , Cat and Dog ....
Animal meowAnimal = new Cat();
and you will need try / catch around explicit throws. In C #, you have a useful as keyword:
Dog myDog = barkAnimal as Dog; Dog myPet = meowAnimal as Dog;
No exception will be thrown, and myDog will not be null, and myPet will be null. Java does not have an equivalent keyword, although you can always use if (meowAnimal instanceof Dog) tests to maintain type safety. (I would suggest that the as keyword generates a bytecode that executes if, assigning zero to is . But maybe .NET has a bytecode instruction that executes the equivalent of as .)
Eddie Feb 12 '09 at 0:33 2009-02-12 00:33
source share