Difference Between assembly.CreateInstance and System.Activator.CreateInstance

  • Thread starter Thread starter John Jenkins
  • Start date Start date
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
 
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...
 
Back
Top