tags:

views:

34

answers:

1

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
{
}
+1  A: 

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;
}
Femaref