Tuesday, January 09, 2007

* CSharp Tip #2 : .NET Namespace Alias

Consider the below code :

 

   1:  using System;
   2:  using System.Collections.Generic;
   3:  using System.Text;
   4:  using FrmwkSystem = System;
   5:   
   6:  namespace VikasGoyal.NameSpace_Qualifier
   7:  {
   8:      class Program
   9:      {
  10:          public class System { }
  11:   
  12:          const int Console = 11;
  13:          const int number = 22;
  14:   
  15:          static void Main(string[] args)
  16:          {
  17:              Console.WriteLine(number); // compile error as Program.Console is visible
  18:              System.Console.WriteLine(number); //compile error as Program.System is visible.
  19:              global::System.Console.WriteLine(number); //OK
  20:              FrmwkSystem::Console.WriteLine(number); //OK
  21:          }
  22:      }
  23:  }






 



The Line 17 and 18 will compilation error because of the names used by local class although in general there is nothing wrong with these lines.



In single program such situations are rare but in multi developer environment where lot of people are working on same program such kind of deadlock situations can occur. Namespace Alias comes to rescue in such situations. As seen from Line 19 and 20, there are two ways of solving such conflicts using Namespace Alias Qualifier (::). For Framework classes directly global can be used but for custom classes if required keyword using can be used to resolve names.

No comments:

Post a Comment