Powered by Blogger.

Sunday, February 23, 2014

Use of Extern Alias in C#.Net



In this post we will discuss about Extern Alias in C#.Net. Also you can check out some posts on:

- How to implement FileUpload Control in Update Panel using asp.net?

- Transaction in SQL Server 2008

- Null Coalescing Operator in C#.Net

The extern alias directive gives you the way for accessing a class which has same name from different physical files. That is  you can reference two versions of assemblies that have the same fully-qualified type names. In  large  projects,you may need to use two or more versions of an assembly in the same application. By using an external assembly alias, the namespaces from each assembly can be wrapped inside root-level namespaces named by the alias, allowing them to be used in the same file.

For example, you may have two class libraries that contain a class with same name. With the extern keyword, you can use both of those classes at once.

extern alias A;
extern alias B;
using System;
class Program
{
    static void Main()
    {  
A.class1.str1 = "First string";
B.class1.str1 = "Second string";
Console.WriteLine(A.class1.str1);
Console.WriteLine(B.class1.str1);
    }
}

//   ClassLibrary1
public class class1
{
    public static string str1;
}
// ClassLibrary2
public class class1
{
    public static string str1;
}
Output:
First string
Second string

The extern alias A and B  must be mapped to the ClassLibrary1 and ClassLibrary2 DLL files.

To reference two assemblies with the same fully-qualified type names, an alias must be specified on the command line, as follows:
/r:A=ClassLibrary1.dll
/r:B= ClassLibrary2.dll 





0 comments

Post a Comment