The global:: qualifier in C#
Today I was a little bit surprised when I was asked if we really needed the global:: qualifier. If you’ve been doing C# for some time, the answer is (absolutely) yes. However, things might not be so clear for a beginner (btw, the question was asked in the context of auto-generated by VS which used it to qualify the name of a base class). The best way to understand it is to write a quick sample where you might really need to use this qualifier:
class Test {
public void SayHi() {
Console.WriteLine("hi global");
}
}
namespace ConsoleApplication1 {
class Test {
public void SayHi() {
Console.WriteLine("hi within");
}
}
class Program {
static void Main(string[] args) {
new Test().SayHi(); //???
}
}
}
The previous sample is valid C# code (notice that we’ve introduced two classes with *similar* names – Test and ConsoleApplication.Test). The real question is: what happens when we create a new Test instance from within the Main method?
In the previous sample, we’ll end up instantiating ConsoleApplication1.Test. And what if we wanted to instantiate Test? Yes, the answer is the global:: qualifier. After showing this example, there really wasn’t any doubt regarding the usefulness of the global::qualifier: you’ll need it in some cases to force the use of a specific type or name.