C# namespaces - What is global:: and when/why to use it?

If you are like me, then you do not care much about namespaces. Hitting alt + enter using resharper gets you want you want most of the time. The only other time where you care about namespaces is when you create a new project. Rarely programmers stumble upon the ::global keyword. The reason why I am writing this post is because I just saw it again.

Basically the global:: keyword is used to access the root namespace. Below is an example where it is neccessary to use global:: in order to distinguish between two implementations. You will rarely see this and most often it is not necessary to do this. In the below example I have added two person classes. When using new Person() the closest implementation is the one used. In order to get the Person implementation in the Person.Person (not Person.Program.Person) namespace, I am using the global:: keyword.

namespace Person
{
    class Person {}

    class Program
    {
        static void Main(string[] args)
        {
            new global::Person.Person(); //Refers to the class above
            var person = new Person(); //Refers to the class below. Could also be referenced by using global::Person.Program.Person.
        }

        class Person {}
    }
}

You will often see the global:: keyword use in system generated code in order to avoid namespace clashing. This way the generated code will not interfere with your written code. An alternative to the above could be using an alias:

using Person2 = Person.Person;