There may be times when we want to use special names for our classes, such as System or Console. It is obvious that these names will cause conflicts with the .NET classes that have similar names. For example, a class named System would hide the System class of the .NET library. Although this is not a common case, C# 2005 allowed for this possibility by adding the namespace alias qualifier operator ( :: ). We can use this operator to search the global namespace for identifiers hidden by types or members in our code.
The:: operator goes between two identifiers, like this:
global::System.Console.WriteLine(“Hello, World!”);
The left – hand identifier that precedes the :: operator is where the search starts. The right – hand identifier is the identifier to look for. When the left – hand identifier is the word “global,” the search starts at the global namespace.
Consider the following example in which a class named System is used. This class name causes a problem that is solved only by using the namespace alias qualifier, like this:
global:: System.Console.WriteLine(mc.myClassNumber);
global::System.Console.WriteLine(ms.mySystemNumber);
If we try to use the following statements instead, we get a compiler error:
System.Console.WriteLine(mc.myNumber); //error
System.Console.WriteLine(ms.myNumber); //error
//Example 5-3.cc
//The namespace alias qualifier
class MyClass
{
int myClassNumber = 123;
public class System
{
public int mySystemNumber = 555;
}
static void Main()
{
//Instantiate classes:
MyClass mc = new MyClass();
System ms = new System();
//Display fields:
global::System.Console.WriteLine(mc.myClassNumber); //123
global::System.Console.WriteLine(ms.mySystemNumber); //555
}
}
Tuesday, March 16, 2010
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment