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 and Downcasting in .NET

"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.


Comments

Author: Phagu Mahato06 Jan 2014 Member Level: Gold   Points : 4

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:

class Birds {
int health = 100;
}

class Sarrow extends Birds { }

class Crow extends Sarrow { }

class parrot extends Sarrow { }

public class Test {
public static void main(String[] args) {
Crow c = new Crow();
System.out.println(c.health);
parrot d = new parrot();
System.out.println(d.health);
}
}



  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name:
    Email: