Unable to cast object of type X to type X
A little over a week ago I had a very serious bug hit me in the gut. I have a project I am currently consumed with that uses several Master Pages in it. Each Master Page has its own derived MasterPage class, just like any code-behind page would have. Suddenly the site did not recognize the MasterPage classes as existing. I spent the better part of two days trying to resolve this issue, then suddenly the problem went away. I think I solved it by clearing the temporary files that visual studio creates during the compile process. I think this forced a full rebuild on the site, which makes sense based on what I found this morning.
I just happen to be parsing through the January 2007 edition of ASP.NET Pro magazine and was reading Chris D’Agostino's article, ASP.NET Tips and Tricks (You will need a subscription) when I read the third tip, 'Look Out for the Master Page Bug'. He was having the same problem and had learned it was a known bug of the compiler. Basically Microsoft knows about it and is working on it. In the meantime you can avoid this problem by setting the compile configuration for your site to include batch="false" in the web.config:
Since the error went away on its own for me I can not say for sure if this will help, but if it never shows up again I will be happy!