Namespace Alias Qualifier (C# Programming Guide)
Written by Thong D. Nguyen Wednesday, 02 March 2011 09:19
Blog - Programming
Source: MSDN
The ability to access a member in the global namespace is useful when the member might be hidden by another entity of the same name.
For example, in the following code, Console resolves to TestApp.Console instead of to the Console type in the System namespace.
class TestApp
{
// Define a new class called 'System' to cause problems.
public class System { }
// Define a constant called 'Console' to cause more problems.
const int Console = 7;
const int number = 66;
static void Main()
{
// Error Accesses TestApp.Console
//Console.WriteLine(number);
}
}
// Error Accesses TestApp.System
System.Console.WriteLine(number);
// OK
global::System.Console.WriteLine(number);
When the left identifier is global, the search for the right identifier starts at the global namespace. For example, the following declaration is referencing TestApp as a member of the global space.
Obviously, creating your own namespaces called System is not recommended, and it is unlikely you will encounter any code in which this has happened. However, in larger projects, it is a very real possibility that namespace duplication may occur in one form or another. In these situations, the global namespace qualifier is your guarantee that you can specify the root namespace.
Example
In this example, the namespace System is used to include the class TestClass therefore, global::System.Console must be used to reference the System.Console class, which is hidden by the System namespace. Also, the alias colAlias is used to refer to the namespace System.Collections; therefore, the instance of a System.Collections.Hashtable was created using this alias instead of the namespace.
using colAlias = System.Collections;
namespace System
{
class TestClass
{
static void Main()
{
// Searching the alias:
colAlias::Hashtable test = new colAlias::Hashtable();
// Add items to the table.
test.Add("A", "1");
test.Add("B", "2");
test.Add("C", "3");
foreach (string name in test.Keys)
{
// Seaching the gloabal namespace:
global::System.Console.WriteLine(name + " " + test[name]);
}
}
}
}
Sample Output
A 1
B 2
C 3
| < Prev | Next > |
|---|
Idioms
- Out of sight, out of mind. (Xa mặt cách lòng)
- Don't count your chickens, before they are hatched. (Chưa đỗ ông Nghè đã đe Hàng tổng)
Who's online
Location
38.107.179.219
38.107.179.219Search Bot
unknown unkno

OS
PHP
MySQL
Time
Caching
GZIP
Members
Content
Web Links




Today
Yesterday
This week
Last week
This month
Last month
All days
