C# Downcast object – Which method to prefer?

(Last Updated On: November 6, 2016)

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
 

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.