Usage of extern alias keyword in C#

Today I heard about Extern keyword in C# for the first time by one of my colleague. it actually eliminates conflicts. It provides a way for you to differentiate between different physical locations of the same class name.  For example you have two separate project in your solution with name of ClassLibrary1 and ClassLibrary2 and also you have two class with the same name and also in the same namespace, like this:

 

(This is in ClassLibrary1 project)

  1. namespace ClassLibrary1
  2. {
  3.     public class SampleClass
  4.     {
  5.         public static string Something;
  6.     }
  7. }

 

(And this is in ClassLibrary2 project)

  1. namespace ClassLibrary1
  2. {
  3.     public class SampleClass
  4.     {
  5.         public static string Something;
  6.         public int Number;
  7.     }
  8. }

So you have referenced these two class library project in another project(for example ConsoleApplication1), and you are going to use these Classes in it, if you type SampleClass complier will conflict these two classes!  

 

Pic

To solve this problem, open the property of the mentioned classes in ConsoleApplication1 and give an specific alias name, like in the picture

Pic

Now in return to the Program class of you console application, use extern key word on top of all defined namespaces like this:

  1. extern alias first;
  2. extern alias Second;
  3. using System;
  4. using System.Collections.Generic;
  5. using System.Linq;
  6. using System.Text;
  7. using System.Threading.Tasks;

Now, you have a specific alias name for each of the namespaces as they are similar, you can use both of the without conflict  like this:

 

  1. extern alias first;
  2. extern alias Second;
  3. using System;
  4. using System.Collections.Generic;
  5. using System.Linq;
  6. using System.Text;
  7. using System.Threading.Tasks;
  8.  
  9. namespace ConsoleApplication1
  10. {
  11.     class Program
  12.     {
  13.         static void Main(string[] args)
  14.         {
  15.             first::ClassLibrary1.SampleClass sampleClass = new first::ClassLibrary1.SampleClass();     
  16.             Second::ClassLibrary1.SampleClass sampleClass2 = new Second::ClassLibrary1.SampleClass();
  17.         }
  18.     }
  19. }


Tags: C#


comments powered by Disqus