Ehsan Ghanbari

Experience, DotNet, Solutions

Usage of extern alias keyword in C#

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();
        }
    }
}

 

About Me

Ehsan Ghanbari

Hi! my name is Ehsan. I'm a developer, passionate technologist, and fan of clean code. I'm interested in enterprise and large-scale applications architecture and design patterns and I'm spending a lot of my time on architecture subject. Since 2008, I've been as a developer for companies and organizations and I've been focusing on Microsoft ecosystem all the time. During the&nb Read More

Post Tags
Pending Blog Posts
Strategic design
Factory Pattern
time out pattern in ajax
Selectors in Jquery
Peridic pattern
How to use PagedList In asp.net MVC
Redis as a cache server
Domain driven design VS model driven architecture
How to query over Icollection<> of a type with linq
What's the DDD-lite?
comments powered by Disqus