Letβs cover extern alias
in C# β a niche but important feature when dealing with multiple assemblies that have conflicting namespaces or types.
π 1. What Is extern alias
?
-
extern alias
allows you to differentiate between two assemblies that contain types with the same fully qualified names. -
It essentially gives an assembly a nickname, so you can specify exactly which type you mean.
-
Usually needed in legacy projects or when referencing multiple versions of the same library.
π 2. Scenario Where You Need It
Imagine you reference two assemblies:
-
LibraryA.dll
containsMyCompany.Logging.Logger
-
LibraryB.dll
also containsMyCompany.Logging.Logger
- Without
extern alias
, the compiler cannot distinguish whichLogger
you mean.
π 3. Setting Up extern alias
Step 1: Add alias in project references
-
In Visual Studio, for one of the conflicting assemblies:
-
Right-click Reference β Properties β Aliases
-
Set it to something like
LibA
(default isglobal
)
-
Step 2: Use extern alias
in code
extern alias LibA; // Use the alias defined in project references
extern alias LibB;
class Program
{
static void Main()
{
LibA::MyCompany.Logging.Logger loggerA = new LibA::MyCompany.Logging.Logger();
LibB::MyCompany.Logging.Logger loggerB = new LibB::MyCompany.Logging.Logger();
loggerA.Log("From LibraryA");
loggerB.Log("From LibraryB");
}
}
-
LibA::
tells the compiler to use theLibA
assembly. -
LibB::
tells the compiler to use theLibB
assembly.
π 4. Key Points
Feature | Notes |
---|---|
extern alias | Lets you differentiate between assemblies with conflicting types |
Requires alias setup in project references | Default alias is global |
Syntax | extern alias AliasName; + AliasName::FullyQualifiedType |
Rarely used | Only when multiple versions of same library are referenced |
π 5. Analogy
-
Imagine two folders with the same file name.
-
You give each folder a nickname and then explicitly say which folderβs file you want:
LibA::Logger
vsLibB::Logger
β Summary:
-
Use
extern alias
when your project references multiple assemblies with conflicting types. -
Define the alias in the reference, then use
extern alias
in code. -
Syntax:
extern alias AliasName;
+AliasName::TypeName
.