Namespace Alias Qualifier (C# Programming Guide)

Blog - Programming

User Rating: / 0
PoorBest 

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.

using System;

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.

class TestClass : global::TestApp

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



Add this page to your favorite Social Bookmarking websites

Add comment


Security code
Refresh

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

We have 37 guests online

Location

 38.107.179.219
 38.107.179.219
Search Bot
 unknown unkno

Relax

Site Ranking


Increase your website traffic with Attracta.com

Quick Search

This Day in History

Poll

What is your current operating system?
 

Weather

Newsletter

Copyright © 2012 Thong D. Nguyen. All Rights Reserved.
Joomla! is Free Software released under the GNU/GPL License.