Difference Between assembly.CreateInstance and System.Activator.CreateInstance

J

John Jenkins

Hi,
I have a fairly simeple question. What are the differences between
Assembly.CreateInstance and System.Activator.CreateInstance? I had read that
one maps to the other, however when I use Assembly.CreateInstance to create
an object that implements an interface it cannot cast to the appropriate
interface type before returning. e.g.

ISubmit lo_MessagingObject=null;

string
l_MessagingType=ConfigurationSettings.AppSettings.Get("messagingtype");

Assembly assembly = Assembly.LoadFrom
(ConfigurationSettings.AppSettings.Get("assemblylocationmessaging"));



// Get all Types available in the assembly in an array

Type[] typeArray = assembly.GetTypes ();

// Walk through each Type and list their Information

foreach (Type type in typeArray)

{

if (type.FullName.CompareTo(l_MessagingType)==0)

{

lo_MessagingObject = (ISubmit)assembly.CreateInstance(l_MessagingType);

}

}



l_MessagingType is a class that implements the ISubmitI Interface.

Fails saying the type is an invalid cast, however the same object type below
casts without any problem. Is this the correct behaviour??



System.Type oType = System.Type.GetType(l_MessagingType);

//create an instance and type cast it to our interface

lo_MessagingObject = (ISubmit)System.Activator.CreateInstance(oType);

thanks
 
J

Jon Skeet [C# MVP]

John Jenkins said:
I have a fairly simeple question. What are the differences between
Assembly.CreateInstance and System.Activator.CreateInstance? I had read that
one maps to the other, however when I use Assembly.CreateInstance to create
an object that implements an interface it cannot cast to the appropriate
interface type before returning.

That usually occurs when the interface occurs in two assemblies, as per
http://www.pobox.com/~skeet/csharp/plugin.html

Might that be the problem in your case?

Type and assembly loading and linking is one of those areas I never
feel I understand well enough, to be honest...
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top