namespace LedgerCommander.A
{
class B
{
static public int a = 7;
}
}
namespace LedgerCommander
{
using LedgerCommander.A;
public class MyClass
{
private int myProperty;
public int MyProperty { get { return LedgerCommander.A.B.a; } }
}
}
LedgerCommander.A.B.a
can be simplified to B.a
LedgerCommander.A.A.a
can be simplified to A.A.a
A.a
then there is an error message
using
is ignoredIs it a feature or a bug in c#?
C# will always prefer a namespace to a class in case of an ambiguity. If you add another class to LedgerCommander.A
, it will become quite obvious: you'll still need to use A.A.a
for accessing class A
, but A.Foo
will work fine.
Also note that this only works because MyClass
is in LedgerCommander
; if you put it into another namespace, you'd have to use using LedgerCommander;
to get the same behaviour.
C# design guidelines are pretty specific about this (https://learn.microsoft.com/en-us/dotnet/standard/design-guidelines/names-of-namespaces):
DO NOT use the same name for a namespace and a type in that namespace.
The type binding doesn't backtrack. If there is an ambiguity, you will need to fully qualify the type name. Sometimes this is as easy as using the namespace and the type name (as in your case), but sometimes you'll need the full path, possibly including an extern alias (ouch). Just don't do it.