The :: Operator and the Global Namespace Qualifier


The :: operator provides an alternative way to access types in namespaces, where namespace aliases are given priority over the usual type qualification. To see what this means, consider the following code:

 using MyNamespaceAlias = MyRootNamespace.MyNestedNamespace; namespace MyRootNamespace { namespace MyNamespaceAlias { public class MyClass { } } namespace MyNestedNamespace { public class MyClass { } } } 

Code in MyRootNamespace can access MyRootNamespace.MyNamespaceAlias.MyClass as follows:

 MyNamespaceAlias.MyClass 

That is to say that MyRootNamespace.MyNamespaceAlias has hidden the alias defined by the using statement, which refers to MyRootNamespace.MyNestedAlias. You can still access this namespace, and the class contained within, but you require different syntax:

 MyRootNamespace.MyNamespaceAlias.MyClass MyNestedNamespace.MyClass 

Alternatively, you can use the :: operator:

 MyNamespaceAlias::MyClass 

Using this operator forces the compiler to use the alias defined by the using statement, and therefore the code refers to MyRootNamespace.MyNestedAlias.MyClass.

You can also use the keyword global with the :: operator, which is essentially an alias to the top-level, root namespace. This can be useful to make it clearer which namespace you are referring to, for example:

 global::System.Collections.Generic.List<int> 

This is definitely the class you expect it to be, the generic List<T> collection class. It definitely isn't the class defined with the following code:

 namespace MyRootNamespace { namespace System { namespace Collections { namespace Generic { class List<T> { } } } } } 

Of course, you should avoid giving your namespaces names that already exist as .NET namespaces, although this problem may arise in large projects, particularly if you are working as part of a large team. Using the :: operator and the global keyword may be the only way you can get access to the types you want.




Beginning Visual C# 2005
Beginning Visual C#supAND#174;/sup 2005
ISBN: B000N7ETVG
EAN: N/A
Year: 2005
Pages: 278

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net