Building A .NET Core 2.0 Class Library

In my previous tutorial, Getting Started with .NET Core 2.0, we learned how to build our first console app using .NET Core 2.0. We also learned how to package and deploy the application so it can be used by other users. 

In this tutorial, we will learn how to build a class library using .NET standard 2.0. We will also see how to call a class library from a console app.

Before reading this tutorial, I recommend completing this previous tutorial: 
Getting Started with .NET Core 2.0 

Note

I’ve used .NET Core 2.0 and Visual Studio 2017 Community version 15.3 for this tutorial. If you don’t have Visual Studio 2017, you may download it here: https://www.visualstudio.com/

What A Class Library Is

Code reusability is one of the key features of a modern programming languages. Software developers often share same functionality among multiple applications to avoid the code redundancy and maintain code standards and quality.

Let’s take an example. Let’s say, Developer A (DevA) creates a Math class that provides functionality to add, multiply, square root, and other math functions.

Now, Developer B (DevB) and Developer C (DevC) also need same functionality. The first option is, either DevB and DevC also write similar code to implement same functionality, or they can use the same code that DevA has written already.

One option is, DevB and DevC copy code from A. That means, there will be three copies of the same code. What if DevA finds a bug and fixes in his/her code? Then, he has to give the changed code to DevB and DevC. What if there are thousands of developers who want DevA’s code?

The best and the simplest way to distribute and reuse what DevA can do is, build a class library and distribute it to DevB and DevC. One of the obvious examples is .NET Framework library. Microsoft has written many class libraries that have common functionality any developer can reuse.

A class library is a package of programs (code that has classes, types, interfaces, and other program elements) that is easily distributable, shareable, and reusable by other developers who want to implement the same functionality. Physically, a class library is a .dll (dynamic link library) file.

Class Library Frameworks

Currently, Visual Studio 2017 supports four types of class libraries project templates, .NET Framework, Universal class library, .NET Core, and .NET Standard. As you may guess, each template targets a specific framework with the exception of .NET Standard. A .NET Standard class library supports all platforms. See Figure 1.

.NET CORE
Figure 1.

In this article, we will build a .NET Standard class library. If you’re not familiar with .NET Standard, I recommend watching this video: What is .NET Standard.

Note

The process of building a class library and consuming from a client app is same, no matter what framework do you choose to build your class library.

Building A .NET Standard Class Library

Now, you’ve installed Visual Studio 2017, let’s build your first Hello World! .NET Core application.

Step 1. Create a Solution and Client App

Create a .NET Core console app. If this is your first time working with .NET Core, read t Getting Started with .NET Core 2.0 and learn how to build your first .NET Core console app.

Note

We will use this app as a client app for the class library.

Step 2. Create a Class Library Project

Now, let’s create a class library project.

Right click on the solution and select Add -> New Project menu option. On the New Project dialog, select .NET Standard in the left side and Class Library (.NET Standard) template in the right side. See Figure 2.

.NET CORE
Figure 2.

Give your project a name, select a folder where you want your project to be created, and click OK. This will create your first .NET Standard class library project.

I give my project name “MCMathLib”.

The Visual Studio project looks like Figure 3.

.NET CORE
Figure 3.

Step 3. Add Class Library Functionality

The default program has a Class1.cs file that has the main code listed. This is where you will be writing more code. I changed the class name to MathClass and add a Calculate method. The Calculate method takes three arguments, two numbers, and one operation type.  See Listing 1.

  1. using System;    
  2.     
  3. namespace McMathLib    
  4. {    
  5.     public class MathClass    
  6.     {    
  7.         public MathClass() { }    
  8.     
  9.         public double Calculate(double num1, double num2, string op)    
  10.         {    
  11.             double result = 0;    
  12.             switch (op)    
  13.             {    
  14.                 case "Add":    
  15.                     result = num1 + num2;    
  16.                     break;    
  17.                 case "Sub":    
  18.                     result = num1 + num2;    
  19.                     break;    
  20.                 case "Mul":    
  21.                     result = num1 * num2;      
  22.                     break;    
  23.                 case "Div":    
  24.                     result = (double)num1 / num2;                      
  25.                     break;    
  26.                 default:           
  27.                     break;    
  28.             }    
  29.             return result;    
  30.         }    
  31.     }    
  32. }    
 

Listing 1.

Now, make sure your class library project is the default project in Visual Studio by Right clicking on McMathLib project and select Set as Startup Project in the menu.

Step 4. Settings

You can set your library settings by right clicking on the library project and select Settings menu item.

This will take you to the settings where you can set application, build, package and other settings. For example, you can select a framework version you want to target. You can change the namespace and assembly name. You can change signing information. See Figure 4.

.NET CORE
Figure 4.

Step 5. Build

Build your project by hitting F5 or Fn+F5 or by selecting Build menu item in Visual Studio. A successful build looks like Figure 5. The McMathLib.dll and other files are created in the Release folder.

Note: Make sure you select the Release build option for the class library project.

.NET CORE
Figure 5.

Consuming A Class Library

Now, let’s see how we can use the above class library functionality in the app.

Step 1. Add Class Library Reference

To use a class library in your application, you must add a reference to the library to access its functionality.

Right click on the project name of your console app in Solution Explorer and select Add ->Reference option. See Figure 4.

.NET CORE
Figure 4.

On the next screen, you will see the McMathLib is already available. That is because the class library is a part of the same solution. See Figure 6.

.NET CORE
Figure 6.

If you don’t see the list, you can use the Browse option and browse to the release folder where the .dll file was created.

We publish the release version of an assembly. Change the build option in your Visual Studio from Debug to Release. See Figure 6.

Step 2. Import Namespace

Before you can use a class library and its classes, you must import the namespace by using the following code.

using McMathLib;

If your class library reference is added correctly, as soon as you start typing “using McM..”, you will see Visual Studio Intellisense will load the namespace in the list. See Figure 7.

.NET CORE
Figure 7.

Step 3. Call Functions

Once the reference is added, all classes and public members of the library should be available in your client app. The code in Listing 2 creates an instance of MathClass and calls its Calculate method.

  1. // Create a class library object and call the Calculate method  
  2. MathClass math = new MathClass();  
  3. double result = math.Calculate(num1, num2, op);  

Listing 2.

Now, remove all code from your console app and type the following code. See Listing 3. The console app reads two numbers and open operation and passes these three parameters to the MathClass.Calculate method and displays the result returned from the class library.

  1. using System;  
  2. using McMathLib;  
  3.   
  4. namespace HelloWorld  
  5. {  
  6.     class Program  
  7.     {  
  8.         static void Main(string[] args)  
  9.         {  
  10.             Console.WriteLine("Hello World!");  
  11.           
  12.             // Read first number   
  13.             Console.Write("Enter Number 1: ");  
  14.             var var1 = Console.ReadLine();  
  15.             // Convert string to int  
  16.             int num1 = Convert.ToInt32(var1);  
  17.             // Read second number  
  18.             Console.Write("Enter Number 2: ");  
  19.             var var2 = Console.ReadLine();  
  20.             // Convert string to int  
  21.             int num2 = Convert.ToInt32(var2);  
  22.             // Read operation type - operator  
  23.             Console.Write("Enter one Operator (Add/Sub/Mul/Div): ");              
  24.             var op = Console.ReadLine();  
  25.   
  26.             // Create a class library object and call the Calculate method  
  27.             MathClass math = new MathClass();  
  28.             double result = math.Calculate(num1, num2, op);  
  29.   
  30.             Console.WriteLine("Result: {0}", result);  
  31.               
  32.             Console.WriteLine("Press any key to exit...");  
  33.             Console.ReadKey(true);              
  34.         }  
  35.     }  
  36. }  

Listing 3.

Step 4. Build and Run

Now, let’s build and run our console app. The output looks like Figure 8.

.NET CORE
Figure 8.

Summary

In this tutorial, we learned how to build a .NET Standard class library using Visual Studio 2017. We also saw how to consume a class library from a console client app.

Further Readings

Here are some useful links on .NET Core.

  • https://www.microsoft.com/net/core
  • http://www.c-sharpcorner.com/technologies/dotnetcore