Suppose you are given a Class.dll assembly compiled from the following simple code:
namespace ClassLibrary
{
public class Class
{
}
}
And consider a different project with the above Class.dll as a project reference and with the following code:
Assembly assembly = Assembly.LoadFrom(@"Class.dll");
Type reflectedType = assembly.GetType("ClassLibrary.Class");
Type knownType = typeof(ClassLibrary.Class);
Debug.Assert(reflectedType == knownType);
The assertion fails, and I don't understand why.
The assertion succeeds if I replace the ClassLibrary.Class with, say, the System.Text.RegularExpressions.Regex class and Class.dll with System.dll, so I'm guessing it has something to do with the project properties ? some Compilation switch perhaps?
Thanks in advance
The problem is load contexts: assemblies loaded via .LoadFrom are kept in a different "pile" than those loaded by Fusion (.Load). The types are actually different to the CLR. Check this link for more detail from a CLR architect.
You're probably loading two different copies of the same assembly.
Compare knownType.Assembly
to reflectedType.Assembly
in the debugger, and look at the paths and versions.
I would imagine that you are not referencing the same assembly that you are loading from disk.
This example (when compiled as Test.exe
) works just fine:
using System;
using System.Reflection;
class Example
{
static void Main()
{
Assembly assembly = Assembly.LoadFrom(@"Test.exe");
Type reflectedType = assembly.GetType("Example");
Type knownType = typeof(Example);
Console.WriteLine(reflectedType == knownType);
}
}