global, ::, huh?

I guess you know the way you can define aliases with the using statement:

using SWF = System.Windows.Forms;

Then you can use the shortcut SWF to reference a type in the namespace. In C# 1, the syntax was like this:

SWF.Button button = new SWF.Button();

Obviously this could be ambiguous, because there could have been any kind of different identifier in scope called SWF. To get rid of this ambiguity, C# 2 introduced the :: qualifier. So now you’ll write the same thing differently:

SWF::Button button = new SWF::Button();

So, the identifier to the left of the :: qualifier (called the namespace alias qualifier, by the way) defines the namespace that is searched for the identifier to the right of the qualifier. This is where global comes into play: this is an identifier you can use if you want to look only at the global namespace. For example, to make absolutely sure that a reference to a class called String can only ever mean (the framework standard) System.String, you could put something like this:

global::System.String mystring = new global::System.String('x', 10);

1 Comment on global, ::, huh?

  1. Johannes Schade // August 23, 2012 at 3:26 am // Reply

    Dear Oliver

    Thank you so much! This makes it very clear. I have not found a better explanation of C#’s :: operator on the Internet.



Leave a Comment

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s