So here is the full details. The exception was
[A]SimpleClassLib.PageHandler cannot be cast to [B]SimpleClassLib.PageHandler. Type A originates from 'SimpleClassLib, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' in the context 'LoadNeither' at location 'D:...\bin\SimpleClassLib.dll'. Type B originates from 'SimpleClassLib, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' in the context 'Default' at location 'D:...\bin\Debug\SimpleClassLib.dll'
The developer mentioned [A]D:...\bin\SimpleClassLib.dll in one of the application config file and built the real app with [B]D:...\bin\Debug\SimpleClassLib.dll so one part of the application created PageHandler instance from [A] and filled the list and the other part was trying to type cast to PageHandler from [B].
The following example will trigger this error easily. Hope this helps someone.
This is the simple class library. Build this as a dll.
// SimpleClassLib.dll
namespace SimpleClassLib
{
public class Foo
{
string Prop1 { get { return "I am Foo!!"; } }
}
}
The following is the console app. The app links to the SimpleClassLib like normal add reference from VS 2008. Also it loads an instance from another path.
// Separate console application App.exe
// Progoram.cs
using SimpleClassLib;
namespace App
{
class Program
{
List<object> myFooList;
Program()
{
myFooList = new List<object>();
Assembly a = Assembly.LoadFile(@"<differentpath>\SimpleClassLib.dll");
Type aFooType = a.GetType("SimpleClassLib.Foo");
ConstructorInfo aConstructor = aFooType.GetConstructor(new Type[] { });
myFooList.Add(aConstructor.Invoke(new object[]{}));
myFooList.Add(aConstructor.Invoke(new object[] { }));
myFooList.Add(aConstructor.Invoke(new object[] { }));
}
void DumpPeculiar()
{
for (int i = 0; i < myFooList.Count; i++)
{
// If one inspects the list in debugger will see a list of
// Foo but this Foo comes from a different load context so the
// following cast will fail. While if one executes the line
// f = myFooList[i] as Foo
// it will succeed
Foo f = myFooList[i] as Foo;
Foo f1 = (Foo)myFooList[i];
}
}
static void Main(string[] args)
{
Program p = new Program();
p.DumpPeculiar();
}
}
}