C # - Why is the is :: - operator associated with the global keyword and not the dot operator?

Coming from the very background of C ++, it takes a while to get used to C #. C # uses the dot (.) Operator more often than the :: - operator (namespace classifier operator in C #) to access namespaces and classes.

C ++ uses the dot (.) Operator to access the members of an instance of a class. On the other hand, the scale resolution operator (: :) is used to access members of a class without an instance of that class. It makes sense to me and is logical and consistent.

While I can take a different approach used in C #, there seems to be at least one instance where I see inconsistency. At least that's how it seems to me. This is related to the global keyword:

global::System.Console.WriteLine("Hello World");

      

Can someone explain to me why the namespace alias specifier should be used with the global keyword instead of the dot operator?

+3


source to share


1 answer


It is not very common, but there are some situations where it is convenient.

Imagine you have a class System

inside the current namespace:

namespace Test {
    static class System {
        public static Do() { }
    }

    class Foo {
        void foo() {
            System.Do(); // What this?
        }
    }
}

      

Do you want to make it more challenging? Add an inner class to System

and call it eg Action

. These are edge cases, of course, and you may not need to use any more global::

, but the language itself should handle this situation. See MSDN for details .

Global namespace aliases are also useful in another situation: when you are referencing two DLLs and they have the same namespaces and classes (for example, because they are just two versions of the same stuff). Then how can you refer to them? Same described here for C ++ . You can change the namespace to include the version number, but it's a pain every time you change it (and AFAIK's automatic refactoring does not work with namespaces), or you can refer to them using two aliases. They will be available, for example, the following:



Version1::CompanyName.MyNamespace.MyClass
Version2::CompanyName.MyNamespace.MyClass

      

Also note that it is good practice (include global: :) when you are generating code (for example, all developer generated code), because you do not know in which script this code will be compiled (then collisions can occur).


Reasoning about ::

and .

well ... this is not a question for SO (if you are so unlucky that Eric is having fun here on SO), but I can guess because they are different things. If the same operator is used .

, then how do you understand the parser using global.System

you want to use a global namespace alias rather than a named class or namespace global

? They should have made a global

reserved keyword and it won't solve the other issue of conflicting hierarchies ...

+1


source







All Articles