Thursday, May 22, 2008

Unable To Cast Object of Type 'x' To Type 'x'

I got this really weird runtime error:

Unable To Cast Object of Type 'x' To Type 'x'

The weird thing was, the 'x' above was the same type.

The best explanation I found to this issue is:
http://www.hanselman.com/blog/FusionLoaderContextsUnableToCastObjectOfTypeWhateverToTypeWhatever.aspx

Basically, I had 2 identical dll files that contain the type 'x' in different paths on the server. One of the dlls was referenced in my project, while the other was loaded using the LoadFrom() function from the System.Reflection.Assembly namespace.
When it was time to cast an object to type 'x', I got the error "Unable To Cast Object of Type 'x' to Type 'x' ".

To resolve this problem, I simply deleted the extra dll reference. This will ensure the same assembly will be used in the project reference and when LoadFrom() is used.

1 comment:

Falkayn said...

Does this have an affect on what Visual Studio shows you when coding? I'd expect you would at least lose intellisense - or is it smart enough to interprete the LoadFrom() function's target?