Search code examples
c#namespacesusing

Problem with identical namespace and class name in C#


        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; } }
            }
        }
  • this works fine, VS studio recognizes that return LedgerCommander.A.B.a can be simplified to B.a
  • if class B is renamed to class A then VS thinks LedgerCommander.A.A.a can be simplified to A.A.a
    • if I try to use A.a then there is an error message
      • 'The type or namespacename 'a' does not exist in the namespace LedgerCommander.A
      • it seems that the using is ignored

Is it a feature or a bug in c#?


Solution

  • 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.