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 aliasallows 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.dllcontainsMyCompany.Logging.Logger -
LibraryB.dllalso containsMyCompany.Logging.Logger
- Without
extern alias, the compiler cannot distinguish whichLoggeryou 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 theLibAassembly. -
LibB::tells the compiler to use theLibBassembly.
π 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::LoggervsLibB::Logger
β Summary:
-
Use
extern aliaswhen your project references multiple assemblies with conflicting types. -
Define the alias in the reference, then use
extern aliasin code. -
Syntax:
extern alias AliasName;+AliasName::TypeName.