Search This Blog

Ambiguous type errors and namespace aliases


posted on Tuesday, May 8, 2012

"The type ... is ambiguous: it could come from assembly ... or from assembly ... Please specify the assembly explicitly in the type name."

This error will occur when a type is available from two different assemblies. The compiler won't know which one to use and that's why the error occurs. Another symptom of this problem is that strange, unexpected things might happen if the two assemblies are switched. When you (unknowingly) declare using the wrong type, you could run into some strange problems since fields and methods that should work, won't work!  Sounds logical, right? But how to fix it...

In my specific case the two DLL's were an external one and the one of the project itself (the one created when the project is built). Therefor I could not just delete one - which could also be a solution - I had to fix this while keeping them both.

To clear up the confusion you need to change the namespace, so that it is clear which DLL should be used. In my case, adding the name of the project (same as the DLL) in front of the namespace fixed the problem.

An example could be:
new System.Web.UI.WebControls.Button()
instead of
new WebControls.Button()

To help prevent these kind of situations you could use namespace aliases, in which you declare a shorter name to the using.

You declare the alias like this:
Using SWW = System.Web.UI.WebControls;

And use it like this:
SWW.Button = new SWW.Button();

This should do the trick!


Could be useful, right?

No comments:

Post a Comment