Solved

Receiving "unable to cast object of type... to type" message when using Reflection to load classes from dll files.

Posted on 2008-10-16
3
1,156 Views
Last Modified: 2013-12-14
Hello, I am trying to load classes from dll files where the class implements the interface IBaseMod, and the class name exists in a Dictionary, objDict.

I am receiving an exception message:  "Exception: Unable to cast object of type 'PluginDll.MovingObect1' to type 'Base.IBaseMod'".

Please help. Below is the layout of the code I am using, and the exact commands I have tried.
//Main program - loads in *.dll files.
 

using System;

using System.Reflection;

using Base;
 

namespace PluginDll

{

    public class LoadMovingObjects : IBaseMod

    {       

    	//do stuff

    	

        public  bool InterfaceFilter(Type typeObj, Object criteriaObj)

	{

	    if (typeObj.ToString() == criteriaObj.ToString())

	        return true;

	    else

	        return false;

        }

        

        public void LoadDLLs(string directory, string chkInterface)

        {

            TypeFilter myFilter = new TypeFilter(InterfaceFilter);

            List<IBaseMod> modules = new List<IBaseMod>();
 

            foreach (string file in Directory.GetFiles(directory, "*.dll"))

            {

                Assembly componentAssembly = Assembly.LoadFrom(file);

                if (componentAssembly != null)

                {

                    try

                    {

                        foreach (Type componentType in componentAssembly.GetTypes())

                        {

                            Type[] InterfaceList = componentType.FindInterfaces(myFilter, chkInterface);

                            

                            {

                                if (InterfaceList.Length > 0)

                                {

                                    Console.WriteLine("\n{0} implements the interface {1}.", componentType.Name, chkInterface);

                                   

                                    foreach (KeyValuePair<int, string> kvp in objDict)

                                    {

                                        Console.WriteLine("Key = {0}, Value = {1}", kvp.Key, kvp.Value);

                                        if (kvp.Value == componentType.Name)

                                        {

                                            int i = kvp.Key;
 

                                            Console.WriteLine("Found match: object {0} with class {1} ", objArray[i, 0], componentType.Name);
 

                                            //The following are the commands I have tried.

                                            

                                            //Object tempObj = Activator.CreateInstance(componentType);  //object is created.

                                            //IBaseMod movingObj = (IBaseMod)tempObj;   //however, receive "Unable to cast object message" here

                                            //Exception: Unable to cast object of type 'PluginDll.MovingObect1' to type 'Base.IBaseMod'.

                                            

                                            //These commands result in the same exception message:                                             

                                            //Type PluginType = componentAssembly.GetType(componentAssembly.GetName().Name + "." + componentType.Name, true, true);

                                            //IBaseMod movingObj = (IBaseMod)Activator.CreateInstance(PluginType);

                                            

                                            //Object tempObj = componentAssembly.CreateInstance("PluginDll.MovingObect1");  //object is created

                                            //IBaseMod movingObj = (IBaseMod)tempObj;   //however, receive "Unable to cast object message" here
 
 
 

					    //These are the only commands that will successfully create the instance and type cast the instance.

					    //As you can see, I have to type in the actual name.  

					    

                                            //PluginDll.MovingObect1 tempObj = new PluginDll.MovingObect1();

                                            //Base.IBaseMod movingObj = (Base.IBaseMod)tempObj;
 

                                            //MovingObect1 tempObj = new MovingObect1();

                                            //BaseMod movingObj = (IBaseMod)tempObj;

                                           

                                        
 
 
 
 
 

--------------------------------
 

//The Interface class
 

using System;
 

namespace Base

{

    public interface IBaseMod

    {

        Vector3 PositionFromDate(DateTime date);

        Vector3 PositionDelta(double timeDelta);

    }

}
 

---------------------------------
 

//The dll file that needs to be loaded
 

using System;

using Base;
 

namespace PluginDll

{

    public class MovingObect1 : IBaseMod

    {

        

        public MovingObect1()

        {

            Console.WriteLine("In MovingObect1 constructor");

        }
 

        Vector3 IBaseMod.PositionFromDate(DateTime date)

        {

            //Do stuff

            return positionVector;

        }

        Vector3 IBaseMod.PositionDelta(double timeDelta)

        {

            //Do stuff

            return positionVector;

        }

      

    }
 

    public class MovingObect2 : IBaseMod

    {

       

        public MovingObect2()

        {

            Console.WriteLine("In MovingObect2 constructor");

        }
 

        Vector3 IBaseMod.PositionFromDate(DateTime date)

        {

            //Do stuff

            return positionVector;

        }

        Vector3 IBaseMod.UpdatePosition(double timeDelta)

        {

            //Do stuff

            return positionVector;

        }

        

    }

Open in new window

0
Comment
Question by:weleda
  • 2
3 Comments
 
LVL 6

Expert Comment

by:divyeshhdoshi
ID: 22738261
You could not cast child object to parent object, you can cast parent object to child object.
but vis-a-versa is not possible automically.


0
 

Author Comment

by:weleda
ID: 22741344
I can cast the object if I use the exact name of the class:
PluginDll.MovingObect1 tempObj = new PluginDll.MovingObect1();
Base.IBaseMod movingObj = (Base.IBaseMod)tempObj;

However I can not cast the object dynamically, this is my problem.
0
 

Accepted Solution

by:
weleda earned 0 total points
ID: 22749971
I found the solution.  The code that loads the assemblies and the interface used for typecasting can not be compiled in the same project.

I found my answer here:
http://www.geocities.com/jeff_louie/OOP/oop13.htm
and here:
http://www.yoda.arachsys.com/csharp/plugin.html
0

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
dangers of teaching programming 10 126
Notepad++ Remote File Management 3 80
How can I debug SSIS using Visual Studio 2008 2 71
Online file editor, manager 6 62
Update (December 2011): Since this article was published, the things have changed for good for Android native developers. The Sequoyah Project (http://www.eclipse.org/sequoyah/) automates most of the tasks discussed in this article. You can even fin…
Jaspersoft Studio is a plugin for Eclipse that lets you create reports from a datasource.  In this article, we'll go over creating a report from a default template and setting up a datasource that connects to your database.
The viewer will learn how to use and create keystrokes in Netbeans IDE 8.0 for Windows.
The viewer will learn how to synchronize PHP projects with a remote server in NetBeans IDE 8.0 for Windows.

867 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

21 Experts available now in Live!

Get 1:1 Help Now