Improving your C# Skills
上QQ阅读APP看书,第一时间看更新

Compatibility mode

Although more than 33K APIs have been added into .NET Standard 2.0, many of the NuGet packages still target .NET Framework, and moving them to .NET Standard is not possible, since their dependencies are still not targeted at .NET Standard. However, with .NET Standard 2.0, we can still add packages which show a warning but don't block adding those packages into our .NET Standard library.

Under the hood, .NET Standard 2.0 uses compatibility shim, which solves the third party library compatibility issue and makes it easy in referencing those libraries. In the CLR world, the identity of the assembly is part of the type identity. This means that when we say System.Object in .NET Framework, we are referencing [mscorlib]System.Object and with .NET Standard, we are referencing [netstandard]System.Object, so if we are referencing any assembly which is part of .NET Framework, it cannot be easily run on .NET Standard and so compatibility issues arise. To solve this problem, they have used type forwarding which provides a fake mscorlib assembly that type forwards all the types to the .NET Standard implementation.

Here is a representation of how the .NET Framework libraries can run in any of the .NET Standard implementations using the type forwarding approach:

On the other hand, if we have a .NET Framework library and we wanted to reference a .NET Standard library, it will add the netstandard fake assembly and perform type forwarding of all the types by using the .NET Framework implementation:

To suppress warnings, we can add NU1701 for particular NuGet packages whose dependencies are not targeting .NET Standard.