C# – extern alias, and ILMerge’d assemblies

Suppose you want to merge an assembly A (AssemblyA.dll) with another assembly B (AssemblyB.dll) with ILMerge into a merged assembly (Merged.dll), and everything works fine until the user of your merged assembly also references that AssemblyB.dll, at which point that user will get Ambiguous reference errors for any reference to types defined in assembly B, for example:

image image

Understandably the compiler is not happy here because it finds duplicated definitions for TypeB under the same namespace in the two versions of the assembly B (the one referenced in the user’s project and the one that’s merged with assembly A).

So how do we get out of this unholy mess?

 

Well, there’s this little known feature in .Net called extern alias which allows you to give referenced assemblies an alias via that little Aliases property in the Properties window for any referenced libraries (one I’m sure we have all seen countless times and wondered what it means).

By default the alias for an assembly is ‘global’, which just means global namespace, but you can change it via the Visual Studio properties window or via command line options to CSC.exe:

imageimage

Now the types defined in the Merged.dll assembly will fall under the Merged namespace and to access them you need to first add a line to your code:

extern alias Merged;

and then anywhere you’re referencing types from the Merged assembly you need to prefix it with Merged:: like the following.

image

You might also want to give AssemblyB an alias just to remove any reasonable doubt which assembly a type comes from whenever you reference a type defined in AssemblyB.

 

Whilst this is a way to get you out of a tight spot, it’s far from a clean solution, and as @BjoernRochel said below, a good general advice is to not merge assemblies that you do not own to begin with:

image