C# downcast object method preference Interview Question : In below program, 2 methods to downcast object has been given. Explain which C# downcast method is better and why? Explain with an example.
Given C# downcast object methods – two way
//Method 1: Down Casting
public static void DrawShapes(Shape s)
{
Circle c = (Circle)s;//downcasting
c.FillCircle();
}
//Method 2: Down Casting
public static void DrawShapesByCheckingCorrectType(Shape s)
{
//Using “is” keyword
if (s is Circle)
{
Circle c = (Circle)s;//downcasting
c.FillCircle();
}
}
Answer:
Method -2 :Out of the given two c# downcast object methods, Method -2, that is DrawShapesByCheckingCorrectType(Shape s) is better because it checking the correct type of object and then call object method. In this case program will not crash if it receives another type of object.
Method -1: DrawShapes(Shape s) also work well, but for the handled object in the function. for example in DrawShapes(Shape s) function, object Circle only is handled. If DrawShapes(Shape s) function receives another type of object, for example “Square” then it will crash the program.
C# downcast object test program using both methods given in question:
Both methods DrawShapes(Shape s) and DrawShapesByCheckingCorrectType(Shape s) handle downcasting for “Circle” object. In this, test program, we have passed other type of object to test i.e. “Square” object. Program will crash on call of DrawShapes(Shape s) method, but will not crash on DrawShapesByCheckingCorrectType(Shape s) call.
//Base class
class Shape
{
//Draw()available to base class Shape and all child classes
public virtual void Draw()
{
Console.WriteLine("Shape");
}
}
class Circle : Shape
{
public override void Draw()
{
Console.WriteLine("Drawing a Circle ");
}
//Speciallized method available to only Circle class
public void FillCircle()
{
Console.WriteLine("Filling a Circle");
}
}
class Square : Shape
{
public override void Draw()
{
Console.WriteLine("Drawing a Square ");
}
//Speciallized method available to only Circle class
public void FillSquare()
{
Console.WriteLine("Filling a Square");
}
}
class Program
{
static void Main(string[] args)
{
//Use Base class reference
Shape baseObj = new Square();//Up-casting.
baseObj.Draw();
//This function will check object type using "is" keyword
DrawShapesByCheckingCorrectType(baseObj);
//this function will not check object type
DrawShapes(baseObj);
}
public static void DrawShapes(Shape s)
{
//It handles only Circle type of object. On any other type
//It will crash.
Circle c = (Circle)s;//downcasting
c.FillCircle();
}
public static void DrawShapesByCheckingCorrectType(Shape s)
{
//use "is" keyword to check if object s is of correct type
//to avoid exception.
if (s is Circle)
{
Circle c = (Circle)s;//downcasting
c.FillCircle();
}
}
}