Global Lookup
NOTE: This article is content that used to be included in the 4th Edition of the book, but was removed in the 5th Edition. A reason it was included in the book was to show how the
global
keyword could be used. However, this is an incredibly rare thing to need, and you can now useglobal
for a globalusing
directive, eliminating the main reasons to include it. Rather than just losing the content forever, I’ve included it here. Fair warning: it is an advanced feature that you will probably never actually use.
When the compiler is trying to figure out what you meant by some name, it will begin by searching the names around it. Consider this awkward code:
public class System // Place this in a namespace besides the global namespace.
{
public void Console() => Console.WriteLine("Hello, World!");
}
When trying to resolve the Console
in Console.WriteLine
, the compiler will find the Console
method (not our old friend, the System.Console
class) and fails to compile.
Even a fully qualified name does not save you here because System.Console
will still find this Console
method in the System
class instead of the Console
class in the System
namespace.
In general, avoid giving things names that lead to confusion like this.
But in a worst-case scenario, you can use global::
to tell the compiler to start the search from the very top:
public class System // Place this in a namespace besides the global namespace.
{
public void Console() => global::System.Console.WriteLine("Hello, World!");
}
This can help resolve strange, tricky situations.