This question already has an answer here:
- Resolving an ambiguous reference 3 answers
How can I see which using
statements provides a class in Visual Studio 2013?
And how can I detect conflicts?
I have this kind of code
foo.cs
:
namespace foo
{
class XmlConverter
{
}
}
bar.cs
:
namespace bar
{
class XmlConverter
{
}
}
And I need to use both foo
and bar
namespaces (both have multiple classes).
EDIT: I know I can rename my classes (or use aliases) but how can I detect this issue(wrong class being used) ? Is it even possible ?
You can use using aliases for this. Syntax looks like this:
using MyAlias = MyNamespace.A
.See Using alias directives and/or How to: Use the Global Namespace Alias
In your case:
of course that only makes sense when your actual namespace consists out of at least two parts or the name of the namespace is much longer and could be shortened without losing readability.
For example shorten
System.IO
toSysIO
orThisIsMyNamespace
toMyNamespace
. Else it's just more yping. With your example it makes more sense to just not have ausing
statement.What is not possible is to somehow have the compiler 'detect' whether you are using foo's XMLConverter or bar's XMLConverter without putting some kind of classifier (be it alias or entire namespace) in front of the classname.
To OP's update: The compiler will let you know that something is wrong. The message is
Class1 is an ambiguous reference between Foo.Class1 and Bar.Class1
.If there is a conflict then the C# will complain with an error. In this case your code should use a fully qualified name as in
new foo.XmlConverter
ornew bar.XmlConverter
.However this is bad practice. If you can you should rename classes to
FooXmlConverter
andBarXmlConverter
.