Prev | Current Page 372 | Next

Jon Skeet

"C# in Depth: What you need to master C# 2 and 3"

4.2 The global namespace alias
There??™s one part of the namespace hierarchy that you can??™t define your own alias for:
the root of it, or the global namespace. Suppose you have two classes, both named
Configuration; one is within a namespace of MyCompany and the other doesn??™t have
a namespace specified at all. Now, how can you refer to the ???root??? Configuration
class from within the MyCompany namespace? You can??™t use a normal alias, and if you
just specify Configuration the compiler will use MyCompany.Configuration.
In C# 1, there was simply no way of getting around this. Again, C# 2 comes to the
rescue, allowing you to use global::Configuration to tell the compiler exactly what
you want. Listing 7.7 demonstrates both the problem and the solution.
using System;
class Configuration {}
namespace Chapter7
{
class Configuration {}
class Test
{
static void Main()
{
Console.WriteLine(typeof(Configuration));
Console.WriteLine(typeof(global::Configuration));
Console.WriteLine(typeof(global::Chapter7.Test));
}
}
}
Listing 7.6 Using :: to tell the compiler to use aliases
Listing 7.7 Use of the global namespace alias to specify the desired type exactly
196 CHAPTER 7 Concluding C# 2: the final features
Most of listing 7.7 is just setting up the situation??”the three lines within Main are the
interesting ones. The first line prints ???Chapter7.


Pages:
360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384