What is downcasting and upcasting ? ( .NET interview questions with videos)
Recently one of our friends who had gone for .NET interviews was asked to explain the difference between downcasting and upcasting. The main intention of the interviewer is to ensure that you know the fundamental of casting. Below goes a detail answer for the same with a video... ENJOY
"Upcasting" means moving subclass object to the parent class object. "DownCasting" is opposite to "Upcasting" moving the parent object to the child object.
"Upcasting" is perfectly valid but "Downcasting" is not allowed in .NET. For instance below is a simple "Customer" parent class which is further inherited by a child class "GoldCustomer".
class Customer
{
}
class GoldCustomer : Customer
{
}
Below is an "upcasting" code where the child parent class gold customer is pushed to the customer class.
Customer obj = new GoldCustomer();
Below is a sample of "downcasting" code where parent class object is tried to move to a child class object, this is not allowed in .NET.
GoldCustomer obj = new Customer(); // not allowed
You can also see the below video on Dotnetspider channel which explains this concept with full demonstration
Hope you will enjoy the video.
Thanks for sharing video tutorial of downcasting and upcasting . I also post some moire detail of downcasting and upcasting as below."UpCasting" means subclass which you can Casting it to SuperClass , so this is legal casting.while DownCasting" means that you want casting a superClass to SubClass. Consider the following example: