Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to control which assembly .Net chooses in a namespace conflict?

I need to (bear with me) for some reason or another use the WinRT version of the System.Text.Encoding namespace. I can add a reference to the assembly manually and such, but it will still use mscorlib's implementation. And I can't completely remove mscorlib apparently.

How can I force my project to use WinRT's System.Text.Encoding.dll instead of mscorlib?

Basically, I need it to generate this piece of IL:

call class [System.Text.Encoding]System.Text.Encoding [System.Text.Encoding]System.Text.Encoding::get_UTF8()

instead of this:

call class [mscorlib]System.Text.Encoding [mscorlib]System.Text.Encoding::get_UTF8()
like image 989
Earlz Avatar asked Sep 20 '12 15:09

Earlz


1 Answers

You need to alias the reference. To do this, go to Solution Explorer and select the reference you want to alias. View the Properties and edit the Aliases field to add a unique alias name.

Alias field in properties with custom alias, myalias

Once you've defined a unique alias, you edit your code to add the extern alias declaration.

extern alias myalias;

Finally, you reference the types via the alias as in (this example aliased System.dll):

myalias::System.Diagnostics.Trace.WriteLine("I referenced this via my alias.");

This now targets the exact reference you want, even if other references also provide a type with the same name and namespace.

For additional info on aliases, see this StackOverflow answer on What use is the Aliases property of assembly references.

like image 84
Jeff Yates Avatar answered Nov 14 '22 23:11

Jeff Yates