Downcasting means casting from a base class (or interface) to a subclass or leaf class.
An example of a downcast might be if you cast from System.Object
to some other type.
Downcasting is unpopular, maybe a code smell: Object Oriented doctrine is to prefer, for example, defining and calling virtual or abstract methods instead of downcasting.
- What, if any, are good and proper use cases for downcasting? That is, in what circumstance(s) is it appropriate to write code that downcasts?
- If your answer is "none", then why is downcasting supported by the language?
Best Answer
Here are some proper uses of downcasting.
And I respectfully vehemently disagree with others here who say the use of downcasts is definitely a code smell, because I believe there is no other reasonable way to solve the corresponding problems.
Equals
:Clone
:Stream.EndRead/Write
:If you're going to say these are code smells, you need to provide better solutions for them (even if they are avoided due to inconvenience). I don't believe better solutions exist.