3

While doing some conversion of .NET Framework 4.6.2 project into .NET Standard project, I noticed that I could add .NET Framework project reference in the .NET Standard project, which doesn't sound correct theoretically.

Why .NET framework project can be added as reference in .NET Standard 2.0 project?

Vy Do
  • 46,709
  • 59
  • 215
  • 313
ggtffg
  • 303
  • 3
  • 20
  • Found some links like: https://stackoverflow.com/questions/57688855/net-framework-dll-not-working-on-net-standard-project but it is not very clear why this is happening? – ggtffg May 28 '20 at 14:22
  • 3
    See the initial [announcement](https://devblogs.microsoft.com/dotnet/announcing-net-standard-2-0/) for .NET Standard 2.0. Specifically, _That’s why we added a compatibility mode that allows .NET Standard projects to reference .NET Framework libraries. While this may not work in all cases (for instance, if the .NET Framework binaries use WPF) we found that 70% of all NuGet packages on nuget.org are API compatible with .NET Standard 2.0_. – Kirk Larkin May 28 '20 at 14:46

1 Answers1

3

When you have .NET Standard project it is compiled against netstandard.dll. Both .NET Framework and .NET Core have netstandard.dll (which provides type-forwarding to mscorlib.dll or System.Runtime.dll). That is why you can use .NET Standard project both in .NET Core and .NET Framework.

So what happens when your .NET Standard project references .NET Framework project (which is compiled against mscorlib.dll)?

If you have references chain .NET Framework -> .NET Standard -> .NET Framework then there is no problem at all because at runtime you have mscorlib.dll with all required types.

But what about .NET Core -> .NET Standard -> .NET Framework references? At runtime you have only System.Runtime.dll. There is no problem with .NET Standard project because netstandard.dll will type-forward to System.Runtime.dll. But the trick is that .NET Core has also mscorlib.dll! And yes, it's also only type-forwarding to System.Runtime.dll types. And everything works. ...unless you will use some .NET Framework type which does not exist in System.Runtime.dll.

Further reading: .NET Framework Compatibility Shim

Sergey Berezovskiy
  • 232,247
  • 41
  • 429
  • 459
  • 3
    A note about cross-platform usage: since this compatibility shim uses the Registry (see [this answer](https://stackoverflow.com/questions/44464937/compatibility-shim-used-by-net-standard-2-0) with diagram), and the Registry is a Windows concept, this won't work for .NET Core running on macOS or Linux. So if your want your .NET Standard library to support cross-platform functionality in .NET Core, keep the references to only other .NET Standard libraries. (Note left for future readers - just expanding on your answer, Sergey.) – Sean Skelly May 28 '20 at 15:38