Well, upcasting is the essence of polymorphism and is beyond reproach
in and of itself, I'd say, although of course it can be abused.
Downcasting is more treacherous. What is bad is to write code that
includes case statements that downcast to various types and run
different code depending on the type. This is bad because it requires
you to modify this code in order to support new derived types, which
defeats one of the major benefits of OOP -- allowing old code to
support new code without requiring modification to the old code.
But it is expected that client code will call into generic methods,
passing in derived types that the generic code has no knowledge of,
and will then downcast a generic return value. That is one way to make
good use of OOP. A good example is storing and retrieving objects to
and from Session in asp.net.
>As a rule of thumb whenever I am up casting and down casting. I always look
>for another solution. I do not have the link where they explains why it is
>best to avoid casting and down casting. If I find it I will let you know.
>> I'm not sure I understand why you think it's not good to upcast and
>> then downcast. That is a very common pattern. The upcast doesn't need
>> to be explicit -- the viewer can simply accept a DataSet and will
>> handle anything derived from DataSet. Many classes in the framework
>> require you to downcast when retrieving an object from a generic
>> method, usually one that returns a System.Object. (Converting from a
>> typed dataset to a generic dataset is upcasting, and converting back
>> is downcasting -- you had these terms reversed in your message.)
>> -- Andy
>> >I have several strongly typed DataSets that are passed to a viewer (a
>> >control that I wrote) The strongly typed dataset are passed one a t a
>> >The user can then Delete/Insert/Update and when they have finished and
>> >the save button, the Strongly typed dataset is returned to the user. This
>> >involved a lot of code duplication in the viewer due to the Strongly
>> >So, I did is to first down cast the strongly typed dataset to a dataset
>> >pass it to the viewer. The user can then Delete/Insert/Update and when
>> >have finished and click the save button, a dataset is returned to them.
>> >user then upcast the dataset to the appropriate strongly typed dataset.
>> >In OO point of view it is not a good idea to Down Cast and then Up cast.
>> >Any ideas or a good pattern to overcome this problem is very much