Note
Access to this page requires authorization. You can try signing in or changing directories.
Access to this page requires authorization. You can try changing directories.
Question
Friday, September 23, 2016 8:06 PM
Does C# support down casting?
All replies (3)
Friday, September 23, 2016 8:12 PM ✅Answered
Just to clarify, you are referring as downcasting as the ability to take an instance of a base class and cast it to an instance of a class that derives from it correct? If so, then this can be accomplished through the as keyword :
// This assumes animal is an instance of an Animal class and Dog derives from Animal
Dog dog = animal as Dog;
The as keyword will return null if the cast fails, so it's generally a good idea to perform some null checking after doing this :
Dog dog = animal as Dog;
if(dog == null)
{
// Something went wrong, the animal wasn't a dog.
}
Saturday, September 24, 2016 7:33 AM ✅Answered
Hi Vinod,
Upcasting (using (Employee)someInstance) is generally easy as the compiler can tell you at compile time if a type is derived from another.
Downcasting however has to be done at run time generally as the compiler may not always know whether the instance in question is of the type given. C# provides two operators for this - is which tells you if the downcast works, and return true/false. And as which attempts to do the cast and returns the correct type if possible, or null if not.
C# provides the is and as operators for casting. the as operator is more efficient because it actually returns the cast value if the cast can be made successfully. The is operator returns only a Boolean value. It can therefore be used when you just want to determine an object's type but do not have to actually cast it.
Example:
Class Shape { }
Class Circle : Shape { }
Circle cir = new Circle();
Shape shp = cir; //upcasting
Circle cir2 = (Circle)shp; //Downcasting
References:
How to: Safely Cast by Using as and is Operators (C# Programming Guide)
Regards
Deepak
Tuesday, September 27, 2016 8:02 AM
Yes.
My guess would be that every computer language which has the concept of sub-typing would support casting to the sub-type.
Do you have an actual problem? Do you have a specific question?