[SOLVED] Error "CS0104: 'DataType' is an ambiguous reference between 'System.ComponentModel.DataAnnotations.DataType' and 'CarlosAg.ExcelXmlWriter.DataType"

Issue

I am getting this error:

“CS0104: ‘DataType’ is an ambiguous reference between
‘System.ComponentModel.DataAnnotations.DataType’ and
‘CarlosAg.ExcelXmlWriter.DataType'”

while running an ASP.NET 4.0 application. Can any one help me on this issue?

Solution

As described in the documentation on Compiler Error CS0104 you’ve got a symbol clash – there are two classes in scope of your source file which are both called DataType – one is in the namespace System.ComponentModel.DataAnnotations and the other is in the namespace CarlosAg.ExcelXmlWriter.DataType'.

You need to do one of the following to resolve this:

1. Explicitly provide the full namespace prefix on each usage, i.e.
System.ComponentModel.DataAnnotations.DataType and CarlosAg.ExcelXmlWriter.DataType:

var cdt = new CarlosAg.ExcelXmlWriter.DataType();
var sdt = new System.ComponentModel.DataAnnotations.DataType();

OR 2. Or use a using directive to alias the namespaces / types, e.g.

using SystemDT = System.ComponentModel.DataAnnotations;
using Carlos = CarlosAg.ExcelXmlWriter;

And then then identify the types with the namespace aliases, e.g..

var dt = new Carlos.DataType();

OR 3. You can also alias at the class level:

using SystemDataType = System.ComponentModel.DataAnnotations.DataType;
using CarlosDataType = CarlosAg.ExcelXmlWriter.DataType;
...
var myObj = new CarlosDataType();

OR 4. If you don’t need to symbols from both namespaces, then delete the unused namespace from the using clause.

My preference would be for Option 2 – it makes it clearer to the reader that there is a namespace clash, without being too verbose (like Option 1 is)

Edit

Re: "I tried by giving full prefix but still I am getting error "CS0138: A
using namespace directive can only be applied to namespaces;
‘CarlosAg.ExcelXmlWriter.DataType’ is a type not a namespace"

(All relating to point #2, above). The error message refers to a situation like this, which isn’t permitted in .Net (but is permitted in Java imports)

// i.e. This won't work, can't import at a class level unless it is aliased
using System.ComponentModel.DataAnnotations.DataType; 

As per my answer, I would recommend that you alias the namespace, and then use the alias prefix to disambiguate between the 2 DataTypes

Answered By – StuartLC

Answer Checked By – Candace Johnson (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *