Compare the two instances of the same class below. The variable instanceA
is created using reflection, while instanceB
is created using a direct reference to the DLL from my VS2012 project.
var a = Assembly.Load(File.ReadAllBytes(@"C:\MyFilePath.dll"));
var t = a.GetType("Namespace.MyClassType");
var instanceA = Activator.CreateInstance(t);
var instanceB = new Namespace.MyClassType();
The problem? These are not equal. The fields in instanceA
and instanceB
are different. Currently my code is working, as long as I'm using instanceB
. But if I change only the letter "B" to "A" then the resulting object is somewhat different which in a later stage breaks the product.
As you probably understand, my task is to use reflection instead of a reference. I have confirmed that the correct constructor is being called.
The problem is that you've got different assemblies - in one case you've loaded an assembly just from a byte array (which happened to be stored on disk as MyFilePath.dll
) and in the other you're referring to the assembly which was loaded into the AppDomain due to the references in your project.
It's not really clear exactly what your context is (where the different assemblies are, etc) but you should look into how you're loading assemblies - that's the crux of it, rather than the Activator.CreateInstance
part.
See more on this question at Stackoverflow