Create your own reusable C# libraries targeting .Net Standard

A while back I tried to “demistify” the main concepts around .Net Core, .Net Standard and .Net Framework, since there were (and still are) a lot of questions and concerns regarding these topics on social media. This time, I’ve decided to go one step further and show you all these concepts at work . This article is intended for beginner .Net developers or self-taught developers like me, which struggle to find a clear path in a jungle full of information that is not always accurate. 

So, I’ve created a new solution in Visual Studio containing a class library targeting .Net Core, a class library targeting .Net Standard, a console application running on .Net Core and a console application running on .Net Framework. The really cool thing is that you can easily package the mentioned class libraries as local NuGet packages, so that’s what I did. And I started to play around with the newly created local NuGet packages.

As a first scenario, I have installed the class library targeting .Net Core as a dependency for the console app running on .Net Core via “Manage NuGet packages”. The installation ran successfully and the console application will run as expected.

The next step was to install the same class library as dependency for the console app running on .Net Framework. Well… this gives an error:

That’s how things work and that’s what i was trying to demystify! If you create a class library targeting .Net Core you will be able to use it only within projects that run on .Net Core as well. Such libraries won’t be compatible with projects running on .Net Framework.

As you would guess, the class library targeting .Net Standard can be successfully installed as dependency in projects targeting both .Net Framework and .Net Core. So if you want to create your own, reusable class libraries that work as expected both in projects targeting .Net Framework and .Net Core, your class library needs to target the .Net Standard.

This article doesn’t take into consideration Portable Class Libraries (PCLs).  PCLs target by definition tha .Net Framework so you will be able to use them only in projects that have the same target as well. So PCLs won’t work with .Net Core projects. If you have PCLs that you really need to reuse in modern .Net applications, bare in mind that PCLs need to be converted into .Net Standard class libraries. That’s not necessarily an easy task, but there is some guidance on this on MSDN.

Last, but not least, in my the easiest way to understand these concepts is to play around with them. So that’s why I’ve created a GitHub repository containing a Visual Studio solution with the necessary projects and the information needed to start playing around with class libraries. So please feel free to clone the repository or download the files and play around.

Leave a Reply

Your email address will not be published. Required fields are marked *