What is the global keyword in CSharp?

During the Christmas break, I received the following question:

What does C# global:: actually do? Code example, from table adapter code:

[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "")]
public partial class AutoTwitDataSet : global::System.Data.DataSet {

The global:: specifier tells the compiler to start looking for the namespace or class starting from the root.  You’ll see it in system-generated code so that the code always works.  That way if you have a namespace right under your current namespace that is the same as the top level namespace the code is trying to access, there won’t be a conflict.

For example, say you have namespace A and namespace B and namespace B.A if I write code in namespace B.A that needs to reference a class in namespace A, without global:: I have no way of getting to it.  If I reference A.classname, the compiler will look for classname in B.A.  With global:: I can tell it to look for classname in global::A.classname and it will find classname in the proper location.

This keyword snuck in during version 2.0.  Since most of us don’t need it, most of us don’t even know it exists.  I didn’t until this past weekend.

Related Post

  • Internationalization – Resource FilesInternationalization – Resource Files Today I'm going to start a series on Internationalization.  Today's post will start with the basics, but I plan to cover such issues as: Using Resources Detecting the language of the browser...
  • Two Interfaces. Same Method. Two meanings.Two Interfaces. Same Method. Two meanings. We've discussed interfaces before, but today I want to dig a little deeper.  I'm going to assume for now that you already know what an interface is and that you know how to implement one on a clas...
  • Readonly variables in CSharp? Really?!Readonly variables in CSharp? Really?! I'm sure most of you are familiar with the keyword "const," which allows you to declare a variable and give it a value and assures that no other code will change the value. const int v = 23; p...
  • using – There’s more there than you are usingusing – There’s more there than you are using If you've spent more than a day programming in CSharp, you have already discovered the need for the using directive: using System; using System.Collections.Generic; using System.Text.RegularExpr...
  • CSharp fixed keywordCSharp fixed keyword Since I've already mentioned my bias against using unsafe mode in this post: Advanced CSharp - unsafe mode I'll skip my normal rant about that.  Just suffice it to say they don't call it "uns...