Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is global::?

Tags:

c#

In C# I see global:: used quite often in auto-generated code. It is not something I have ever used myself so I don't know what the purpose is. Can someone explain this?

like image 767
Sachin Kainth Avatar asked Oct 16 '22 10:10

Sachin Kainth


2 Answers

global refers to the global namespace, it can be used to solve problems whereby you may redefine types. For example:

class foo
{
    class System
    {

    }

}

If you were to use System where it would be locally scoped in the foo class, you could use:

global::System.Console.WriteLine("foobar");

to access the global namespace.

Example

using System;

class Foo
{
    public void baz()
    {
        Console.WriteLine("Foo 1");
    }
}

namespace Demo
{
    class Foo
    {
        public void baz()
        {
            Console.WriteLine("Foo 2");
        }
    }

    class Program
    {
        protected static global::Foo bar = new global::Foo();

        static void Main(string[] args)
        {
            bar.baz(); // would write Foo 1 to console as it refers to global scope
            Foo qux = new Foo();
            qux.baz(); // would write Foo 2 to the console as it refers to the Demo namespace
        }
    }
}
like image 127
chrisw Avatar answered Oct 19 '22 04:10

chrisw


It's a sometime-necessary prefix indicating the root namespace.

It's often added to generated code to avoid name clashes with user code.

For example, imagine you had a class called System, but then you wanted to use System.String. You could use global::System.String to differentiate.

I believe the :: comes from C++ where it's used as a namespace separator.

In practice I've never used it, other than in generating code. Note that you can also get around some conflicts via using aliases. For example using String = System.String;

like image 36
Drew Noakes Avatar answered Oct 19 '22 05:10

Drew Noakes