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:

  1. LibraryA.dll contains MyCompany.Logging.Logger

  2. LibraryB.dll also contains MyCompany.Logging.Logger

  • Without extern alias, the compiler cannot distinguish which Logger 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 is global)


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 the LibA assembly.

  • LibB:: tells the compiler to use the LibB assembly.


πŸ“Œ 4. Key Points

FeatureNotes
extern aliasLets you differentiate between assemblies with conflicting types
Requires alias setup in project referencesDefault alias is global
Syntaxextern alias AliasName; + AliasName::FullyQualifiedType
Rarely usedOnly 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 vs LibB::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.