Reputation: 1185
I'm finding some frustration with the way C# handles namespaces when I want to reference a class whose class name happens to be identical to part of the current class's namespace. This will produce a compiler error, "'Class' is a namespace but is used like a type".
Consider the following code sample, which demonstrates the problem:
namespace A.B.C
{
public class Y
{
}
}
namespace X.Y.Z
{
public class Class1
{
public Y MyProp;
}
}
In this case, I want to use the class "Y" from the namespace "A.B.C". But because "Y" is also one of the parts of the namespace, C# treats "Y" as a namespace, not a type.
I can get around this by fully qualifying the class name, "A.B.C.Y", or using an alias, but my general preference would be for C# not to treat "Y" as a namespace in this context. Often I have code, such as test code, that contains similar namespaces as classes its testing, and this kind of class/namespace collision means having to be a lot more verbose in setting things up.
I'm not sure what the process is called, but it seems that in resolving classes and namespaces, C# will walk up the namespaces until it finds a part of the namespace that matches. In this case, it walks up and finds Y. Is there a way to tell C# not to walk up, not to allow this partial namespace matching?
Upvotes: 2
Views: 888
Reputation: 274460
If you write using A.B.C;
(the namespace that Y
is in) inside namespace X.Y.Z
, the error goes away:
namespace X.Y.Z
{
using A.B.C;
public class Class1
{
public Y MyProp;
}
}
Upvotes: 8