Blog

Filter posts by Category Or Tag of the Blog section!

Usage of extern alias keyword in C#

Wednesday, 16 October 2013

Today I heard about the Extern keyword in C# for the first time by one of my colleagues. 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 projects in your solution with the 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)

 

namespace ClassLibrary1
{
    public class SampleClass
    {
        public static string Something;
    }
}

 

(And this is in ClassLibrary2 project)

 

namespace ClassLibrary1
{
    public class SampleClass
    {
        public static string Something;
        public int Number;
    }
}

 

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 compiler will conflict these two classes!  

 

Pic

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

Pic

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

 

extern alias first;
extern alias Second;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
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 them without conflict  like this:

 

extern alias first;
extern alias Second;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            first::ClassLibrary1.SampleClass sampleClass = new first::ClassLibrary1.SampleClass();     
            Second::ClassLibrary1.SampleClass sampleClass2 = new Second::ClassLibrary1.SampleClass();
        }
    }
}

 

Category: Software

Tags: C#

comments powered by Disqus