Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create an extern alias to mscorlib

I have a third party lib that provides a System.Collections.Generic.IReadOnlyCollection type for compatibility purposes with .NET 4.0 applications. However, if you link this library in a .NET 4.5 application, you get the error

  • The type 'System.Collections.Generic.IReadOnlyCollection' exists in both 'd:\3rdParty\net40\3rdPartyLib.dll' and 'c:\Program Files (x86)\Reference Assemblies\Microsoft\Framework.NETFramework\v4.5\mscorlib.dll'

One way to solve those kinds of conflicts is to specify an extern alias to the library you would like to use, and use this alias to disambiguate which assembly we are refering to. Specifying an extern alias involves clicking on the library reference in the project's References folder, pressing F4 to show the property grid, then specify another name in the "Aliases" field. However, the problem is that mscorlib doesn't appear in the Reference List in Visual Studio. Attempting to add it manually results in the error

  • A reference to 'mscorlib' could not be added. This component is already automatically referenced by the build system.

So, given all of the above, the question is: How can I specify an external alias to mscorlib, given that I cannot see and not even add it in the project's reference list?

like image 777
Cesar Avatar asked Dec 21 '14 12:12

Cesar


1 Answers

The answer was in the same line as in How to create an extern alias for System.Core?

We have to manually edit the project's .csproj file, then look for the ItemGroup section that lists all the references to the project. In this section, we have to manually add a reference to mscorlib and specify the aliases we would like to use, as in

<ItemGroup>
    <Reference Include="mscorlib">
      <Aliases>global, mscorlib</Aliases>
    </Reference>

     ... other references

</ItemGroup>

Afterwards, we can go to the source file where the error was happening, and add

extern alias mscorlib;

to the top of the file. Finally, whenever we had the error "... The type 'System.Collections.Generic.IReadOnlyCollection' exists in both..." we can just specify the full namespace of the mscorlib reference, as in

mscorlib::System.Collections.Generic.IReadOnlyCollection<double> bla;

of course, such lenghtly lines can also be made shorter by specifying a using directive in the top of the file like

using ms = System.Collections.Generic;

and then use it as

ms.IReadOnlyCollection<double> bla;
like image 133
Cesar Avatar answered Nov 16 '22 17:11

Cesar