I have two distinct namespaces, each with a Thing class:
namespace First.Second.Third
{
public class Thing { }
}
namespace Fourth.Fifth.Sixth
{
public class Thing { }
}
Now I try to use Thing elsewhere, and of course the compiler complains due to the ambiguous reference to that class:
namespace ConsoleApp1
{
using First.Second.Third;
using Fourth.Fifth.Sixth;
internal static class MainEntryPoint
{
internal static void Main(string[] args)
{
var x = new Thing(); // Complaint.
}
}
}
If I add an alias to one of the namespaces in the using directive, the compiler error goes away:
using MyAlias = First.Second.Third;
using Fourth.Fifth.Sixth;
Now the compiler thinks I'm referring to Fourth.Fifth.Sixth.Thing when I do var x = new Thing();.
Why does the compiler resolve the ambiguity simply by adding an alias to one of the namespaces? Why does it automatically pick the namespace that I did not alias?
I expected this to be well documented and covered many times before on SO and elsewhere, but I can't find the answer. Can someone help me find the dupe if there is one?
EDIT: I'm not on the same page as everyone I guess. Here's a real-world example that might help:
If I have two people named "Bob", and I just say "here, give this to Bob", you won't know whom to give it to. If I say, well one is "Bob Smith" and the other is "Bob Johnson", of course I can now say "here, give this to Bob Smith." Now, if I say, "let's call Bob Smith by a new name: Bob Brady". If I then say "here, give this to "Bob", that is still ambiguous. See my point?
x.Thingto get a thing fromFirst.Second.ThirdandThingwithoutxrefers toFourth.Fifth.Sixth.Thing. They each have a unique name so no ambiguity.Thingthe compiler didn't know which one you meant. The alias fixed that. If you didnew First.Second.Third.Thingit would have never complained in the first place. It stops being ambiguous because you "promised" the compiler that you will always refer toFirst.Second.Third.ThingasMyAlias.Thing