Instantiating an object from a DLL causes casting exceptions

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

What is the correct method by which to load an object from a DLL? If I have
an application called "DLLTest" and a class library project called "BigDLL",
and that BigDLL contains a class called "Cow", I do the following in DLLTest:

using BigDLL;
namespace DLLTest
{
Assembly loader = Assembly.LoadFile(PathToBigDLL.dll);
foreach (Type t in loader.GetTypes())
{
if (t.Name == "Cow")
{
Cow c = (Cow)loader.CreateInstance(t.FullName);
}
}
}

And for reference, Cow.cs in BigDLL contains the following:
namespace BigDLL
{
public class Cow
{
public Cow()
{
}
}
}

I am given the following exception at the line 'Cow c = (Cow)...':
Unable to cast object of type 'BigDLL.Cow' to type 'BigDLL.Cow'.

How are objects supposed to be loaded in such a situation? The purpose of
this exercise is to be able to load an updated version of Cow, if somebody
recompiles the BigDLL, we would load in the new DLL that was spit out by the
compiler. Is there a reason why this isn't possible, or am I just using the
wrong methods?
 
Hi

Are you using the same dll?
"Cow c" is using the DLL with using directive.
And the Assembly.LoadFile used another DLL.

So although the two types are of the same name(BigDLL.Cow), but they can
not be casted from one to another.

If you still have any concern, please feel free to post here.

Best regards,

Peter Huang
Microsoft Online Partner Support

Get Secure! - www.microsoft.com/security
This posting is provided "AS IS" with no warranties, and confers no rights.
 
It might be a poor example; but, what are you trying to do? If you've made a
reference to BigDLL with "using BigDLL;" why would you want to iterate the
types in that DLL? You have to know what type it is in order to assign it to
anything other than an Object reference (e.g. Cow c =
(Cow)loader.CreateInstance(t.FullName);)

CreateInstance can fail in different ways. If the type does not have a
default constructor, obviously, that CreateInstance override will generate an
exception.

To avoid a casting exception you can use the as operator:

Cow c = loader.CreateInstance(t.FullName) as Cow;

If CreateInstance didn't create the type "Cow" c will be null.
 
Back
Top