Monday, December 7, 2009

C# Inheritance, Typecasting, and Reflection

Did you know that an inherited class cannot be cast into its base class so that reflection will think it's working with the base class?



This proved a minor nuisance as the code had a simplistic work-around, but this might not always be the case.



Below is an example of what I'm talking about:


using System.Reflection;
public static class UtilityClass
{
    public static object GetResult(object workClass)
    {
        string ResultingClassName = "Result" + workClass.GetType().ToString();
        Type provider = Type.GetType(ClassName, true);
        ConstructorInfo constructor = provider.GetConstructor(new Type[0]);
        return constructor.Invoke(new object[0]);
    }
}


public class ResultClass
{
    public ResultClass()
    {
    }
}
public class Class
{
    public ResultClass GetResult()
    {
        return (ResultClass)UtilityClass.GetResult(this);
    }
}
public class ChildClass : Class
{
    public void DoTest()
    {
        ResultClass x = ((Class)this).GetResult();
    }
}

The above code will fail with an exception when DoTest() in ChildClass is called, because it will try to create ResultChildClass, which does not exist.  No matter how you cast, you can't get this to work, because the GetResult method of UtilityClass, using Reflection, will always identify the object for what it really is.

In my case, the solution was to simply create a new "Class" object and copy the base of the ChildClass object into it, then call the "GetResult" method to get my "ResultClass".

No comments:

Post a Comment