Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Namespace Alias qualifier (::) vs Dereferencing Operator (.)

Quick and simple question. I kind of understand what the Namespace Alias qualifier does, it's for accessing members in a namespace, however so does the dereferencing operator. I am really baffled as to the difference in this situation, why you would use one over the other, or how they each accomplish the same thing.

using colAlias = System.Collections;  namespace myns {     class TestApp     {         static void Main()         {             colAlias.Hashtable test = new colAlias.Hashtable();             colAlias::Hashtable test1 = new colAlias::Hashtable();         }     } } 
like image 899
Francisco Aguilera Avatar asked Aug 28 '12 06:08

Francisco Aguilera


1 Answers

This is a corner case :: (like the @ prefix) is there to deal with the fairly rare occurrences where a name conflicts between namespaces, classes and keywords.

:: only works for namespaces (and namespace aliases), while .. works for both namespaces and subclasses. Most places where you'd need it you'd be better off using a different name instead, but that isn't always an option.

global:: is a special case that's most often seen in auto-generated code - it resets the referenced namespace to the root.

For instance, suppose you auto-generate some code (maybe for a forms app, EF, or similar) and your app uses the namespace YourCompany.Application. Now one of your customers (using your auto-generation) decides to add their own namespace in their app TheirCompany.YourCompany.Application. Now all your auto code fails because when it compiles .Net doesn't know whether to use your namespace or theirs.

To fix this generate code with global::YourCompany.Application, then those that use your auto-generator can use whatever namespace they like and not conflict.

I think Microsoft added global:: because they expected some .Net customers to add namespaces like System.

like image 133
Keith Avatar answered Sep 21 '22 13:09

Keith