Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Type ambiguity between two referenced assemblies

Tags:

c#

I have the the following problem that starts to drive me nuts. I have a class say Class1 in Assembly1. I moved Class1 to Assembly2 and obsoleted Class1 in Assembly2 (Kept the same namespace and I can't remove it now to avoid a breaking change for my users).

Now I have a unit test assembly, TestAssembly2 that references both assemblies Assembly1 and Assembly2. Now I get a compilation problem Class1 ambiguity when trying to use Class1 in my unit tests. This makes sense as I have two Class1 in both assemblies Assembly1 and Assembly2.

QUESTION Is there a way to tell the compiler to use Class1 defined in Assembly2 (as the one in Assembly1 is obsolete) not Assembly1?

EDIT I can't use type forwarding as Assembly1 must not have a reference to Assembly2 :(

like image 362
GETah Avatar asked Jan 16 '23 07:01

GETah


2 Answers

You could try the TypeForwardedTo Attribute.

[assembly:TypeForwardedTo(typeof(Class1))]

That way you can move the type to another assembly entirely without breaking anything. You don't even need to rebuild referencing assemblies, because the runtime handles the forwarding for you.
See here for more information:
Type forwarding using TypeForwardedTo attribute

EDIT: If you can't reference Assembly2 from Assembly1, you can define an extern alias:
MSDN Documentation for extern alias (C# Reference)

You can define them by selecting the reference to the assembly in the Solution explorer and editing the Aliases in the property Window.

You'd then just need to qualify your type with yourAlias::Class1.

like image 192
Botz3000 Avatar answered Jan 29 '23 10:01

Botz3000


You should alias your assembly.

Under the references node of your consuming project, select Assembly2 and set a different "aliases", "a2" for example.

Also add extern alias a2 in your code.

Than, when you need to refer to this type, use a2::YourName.Class2. This will remove disambiguity.

Jon Skeet has already explaining how this works

like image 45
Steve B Avatar answered Jan 29 '23 11:01

Steve B