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?
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
}
}
}
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With