Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# cast derived class to base class exception via reflection

Tags:

c#

.net

I have an app that creates classes dynamically using reflection. When deployed, I get an exception when casting a derived class to its base class. It only happens on 1 in 100 machines. All the classes are in the same assembly. Below are some code snippets and output from a logging message just prior to the casting exception. I'm at my wits end, any help greatly appreciated.

//Parent class
namespace Framework.DataModel
{
    [Serializable]
    public class DataTreeRequest : TreeNode, IDirtyListener, ISerializable
    {
        ....
    }
}

// Derived Class    
namespace Framework.DataModel
{
    [Serializable]
    public class CADElementRequest : DataTreeRequest
    {
        public CADElementRequest(String name) : base(name){}
    }
}


// Method that uses reflection to create class and then cast to its base class
namespace Framework.DataModel
{
    [Serializable]
    public class DataModelBuilder : CoreBuilder
    {
        ...

        protected DataTreeRequest CreateDataTreeRequest(String asmName, String inName, String inType, String inSourceName)
        {
            DataTreeRequest dtr = null;

            Assembly asm = Assembly.LoadFrom(asmName);
            if (asm == null)
            {
                throw new BaseException("Can't find assembly " + asmName);
            }

            Type requestType = asm.GetType(inType);
            if (requestType == null)
            {
                throw new BaseException("Can't find class of type " + inType + " in assembly " + asmName);
            }

            // Call the constructor for the tree node that takes the xml node as an argument
            Type[] constructorArgsTypes = new Type[1];
            constructorArgsTypes[0] = typeof(String);
            ConstructorInfo constructorInfo = requestType.GetConstructor(constructorArgsTypes);
            if (constructorInfo == null)
            {
                throw new BaseException("Can't find constructor for type " + inType + " that takes a String param");
            }

            Object[] constructorArgs = new Object[1];
            constructorArgs[0] = inName;
            Object newObj = constructorInfo.Invoke(constructorArgs);

            // Code fails on this line trying to cast derived class to base class on 1 in 100 machines
            dtr = newObj as DataTreeRequest;
            if (dtr == null)
            {
                throw new BaseException("Can't cast newObj to type DataTreeRequest. newObj = " + newObj + ", Type = " + newObj.GetType().ToString());
            }

            dtr.InSource = inSourceName;

            return dtr;
        }
    }
}

Logging output on failed machine:

Message = Found assembly=Framework.DataModel, Version=1.0.5885.31486, Culture=neutral, PublicKeyToken=null

Message = newObj AssemblyQualifiedName=Framework.DataModel.CADElementRequest, Framework.DataModel, Version=1.0.5885.31486, Culture=neutral, PublicKeyToken=null, BaseType==Framework.DataModel.DataTreeRequest, FullName==Framework.DataModel.CADElementRequest

BaseException: Can't cast newObj to type DataTreeRequest. newObj = Name=Substations;InType=;InName=Substations;OutName=Substations;InSource=;OutSource=;, Type = Framework.DataModel.CADElementRequest

like image 546
Brian Selle Avatar asked Feb 13 '16 15:02

Brian Selle


People also ask

What C is used for?

C programming language is a machine-independent programming language that is mainly used to create many types of applications and operating systems such as Windows, and other complicated programs such as the Oracle database, Git, Python interpreter, and games and is considered a programming foundation in the process of ...

What is the full name of C?

In the real sense it has no meaning or full form. It was developed by Dennis Ritchie and Ken Thompson at AT&T bell Lab. First, they used to call it as B language then later they made some improvement into it and renamed it as C and its superscript as C++ which was invented by Dr.

What is C in C language?

What is C? C is a general-purpose programming language created by Dennis Ritchie at the Bell Laboratories in 1972. It is a very popular language, despite being old. C is strongly associated with UNIX, as it was developed to write the UNIX operating system.

Is C language easy?

C is a general-purpose language that most programmers learn before moving on to more complex languages. From Unix and Windows to Tic Tac Toe and Photoshop, several of the most commonly used applications today have been built on C. It is easy to learn because: A simple syntax with only 32 keywords.


1 Answers

try to replace

Assembly asm = Assembly.LoadFrom(asmName);
if (asm == null)
{
    throw new BaseException("Can't find assembly " + asmName);
}

Type requestType = asm.GetType(inType);

with

Type requestType = Type.GetType(inType)

where inType is assembly qualified name https://msdn.microsoft.com/en-us/library/system.type.assemblyqualifiedname(v=vs.110).aspx

If you need load assembly that is not referenced by project consider using Assembly.Load method.

About disadvantages of using Assembly.LoadFrom read Remarks section in https://msdn.microsoft.com/EN-US/library/1009fa28(v=VS.110,d=hv.2).aspx

like image 55
Dmitry Kolchev Avatar answered Oct 18 '22 04:10

Dmitry Kolchev