Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamic Casting based on Type information

Tags:

c#

casting

I want to do an explicit cast using Type information from one array to another which is related by inheritance. My problem is that while casting using Type information the compiler throws error, but my requirement is to dynamically cast based on the Type information provided.

Please Help

class Program
{
    static void Main(string[] args)
    {
        Parent[] objParent;
        Child[] objChild = new Child[] { new Child(), new Child() };
        Type TypParent = typeof(Parent);

        //Works when i mention the class name
        objParent = (Parent[])objChild;

        //Doesn't work if I mention Type info 
        objParent = (TypParent[])objChild;
    }
}

class Parent
{
}

class Child : Parent
{
}
like image 495
AbrahamJP Avatar asked Jun 17 '10 14:06

AbrahamJP


1 Answers

The only way you can cast dynamically is with reflection. Of course you can't cast objChild to TypParent[] - you are trying to cast an array of Child to an array of Type.

You could use the .Cast<T>() method called with reflection to achieve this:

 MethodInfo castMethod = this.GetType().GetMethod("Cast").MakeGenericMethod(typeParent);
 object castedObject = castMethod.Invoke(null, new object[] { objChild });

If you need one for non-IEnumerable types, make an extension/static method:

public static T Cast<T>(this object o)
{
    return (T)o;
}
like image 107
Femaref Avatar answered Oct 04 '22 00:10

Femaref