13.07.2015 Views

C# in Depth

C# in Depth

C# in Depth

SHOW MORE
SHOW LESS
  • No tags were found...

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Namespace aliases195List<strong>in</strong>g 7.6us<strong>in</strong>g System;us<strong>in</strong>g W<strong>in</strong>Forms = System.W<strong>in</strong>dows.Forms;us<strong>in</strong>g WebForms = System.Web.UI.WebControls;class W<strong>in</strong>Forms{}class Test{static void Ma<strong>in</strong>(){Console.WriteL<strong>in</strong>e (typeof (W<strong>in</strong>Forms::Button));Console.WriteL<strong>in</strong>e (typeof (WebForms::Button));}}Instead of W<strong>in</strong>Forms.Button, list<strong>in</strong>g 7.6 uses W<strong>in</strong>Forms::Button, and the compiler ishappy. If you change the :: back to . you’ll get a compilation error. So, if you use ::everywhere you use an alias, you’ll be f<strong>in</strong>e, right? Well, not quite…7.4.2 The global namespace aliasUs<strong>in</strong>g :: to tell the compiler to use aliasesThere’s one part of the namespace hierarchy that you can’t def<strong>in</strong>e your own alias for:the root of it, or the global namespace. Suppose you have two classes, both namedConfiguration; one is with<strong>in</strong> a namespace of MyCompany and the other doesn’t havea namespace specified at all. Now, how can you refer to the “root” Configurationclass from with<strong>in</strong> the MyCompany namespace? You can’t use a normal alias, and if youjust specify Configuration the compiler will use MyCompany.Configuration.In <strong>C#</strong> 1, there was simply no way of gett<strong>in</strong>g around this. Aga<strong>in</strong>, <strong>C#</strong> 2 comes to therescue, allow<strong>in</strong>g you to use global::Configuration to tell the compiler exactly whatyou want. List<strong>in</strong>g 7.7 demonstrates both the problem and the solution.List<strong>in</strong>g 7.7Use of the global namespace alias to specify the desired type exactlyus<strong>in</strong>g System;class Configuration {}namespace Chapter7{class Configuration {}}class Test{static void Ma<strong>in</strong>(){Console.WriteL<strong>in</strong>e(typeof(Configuration));Console.WriteL<strong>in</strong>e(typeof(global::Configuration));Console.WriteL<strong>in</strong>e(typeof(global::Chapter7.Test));}}Licensed to Rhona Hadida

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!