Runtime TypeCasting in C#

IDE: VS2010, C# .NET 4.0

I am wondering is there any way to typecast the object in the way variable passed in it for eg:

#CODE BLOCK 1  
    private void ReArrangeShapeLocation(Shape currentControl, double scalePrecentageHeight, double scalePrecentageWidth)
    {
        //here I need to type cast control according to their type

        //example code
        int cX = (currentControl as RectangleShape).Location.X;
        int cXo = (currentControl as OvalShape).Location.X;  
        //Computation code.
    }  

Here Shape class is available in c# namespace

Microsoft.VisualBasic.PowerPacks  

and RectangleShape and OvalShape are child classes of Shape class.

So in above code if I pass

ReArrangeShapeLocation(somRectrangleShape1,14,34);
ReArrangeShapeLocation(somOvelShape1,15,15);  

As here i am passing rectangle and oval shape in same function to get their location in the function (see code block #1), I need to type cast the Shape object accordingly.

Is there any way in c# to typecast the shape object according to child class whatever I pass in ReArrangeShapeLocation function.

#CODE BLOCK 1  
    private void ReArrangeShapeLocationDYNAMIC(Shape currentControl, double scalePrecentageHeight, double scalePrecentageWidth)
    {
        //here I need to type cast control according to their type

        //example code
        int cX = (currentControl as Typeof(currentControl)).Location.X;

    }      

I know it can be done using switch case which I don’t want. Also I know in c# this might be done using Reflaction, But I don’t know.


Source: .net

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.