Mastering C# Class Libraries: Step-by-Step Examples

In the world of C#, a class library is a collection of reusable classes, interfaces, and other types that can be shared across multiple projects. It's a powerfu...

In the world of C#, a class library is a collection of reusable classes, interfaces, and other types that can be shared across multiple projects. It's a powerful feature that promotes code reusability, maintainability, and separation of concerns. Let's dive into the concept of a class library in C# with a practical example.

Easy School Library Orientation Plan (No Stress Back to School)
Easy School Library Orientation Plan (No Stress Back to School)

Before we start, ensure you have Visual Studio installed. We'll create a simple class library project and then reference it in a console application to demonstrate its usage.

Simplified Classroom Library Checkout System for Teachers
Simplified Classroom Library Checkout System for Teachers

Creating a Class Library Project

Our first step is to create a new Class Library (.NET Core) project. In Visual Studio, go to File > New > Project, then select ".NET Core" and "Class Library (.NET Core)". Name your project, for example, "MyClassLibrary", and choose a location to save it.

Easy Classroom Library Checkout System - Learn Grow Blossom
Easy Classroom Library Checkout System - Learn Grow Blossom

Once the project is created, you'll see a single class file, "Class1.cs". Rename this file to something more descriptive, like "MathUtils.cs", and update the class name to "MathUtils".

Creating Reusable Methods

the library dewey decimal system is shown in this table, which contains several different
the library dewey decimal system is shown in this table, which contains several different

Let's create a simple math utility class with methods for adding, subtracting, multiplying, and dividing two numbers. Open the "MathUtils.cs" file and replace its contents with the following code:

public static class MathUtils
{
    public static int Add(int a, int b)
    {
        return a + b;
    }

    public static int Subtract(int a, int b)
    {
        return a - b;
    }

    public static int Multiply(int a, int b)
    {
        return a * b;
    }

    public static float Divide(int a, int b)
    {
        if (b == 0)
        {
            throw new ArgumentException("Cannot divide by zero");
        }

        return (float)a / b;
    }
}

These methods are now ready to be used in any project that references our class library.

Building and Using the Class Library

How Simplifying Library Orientations Will Simplify Library Management -Looking Backward with No Sweat Library
How Simplifying Library Orientations Will Simplify Library Management -Looking Backward with No Sweat Library

To use our class library in another project, first, we need to build it. Right-click on the "MyClassLibrary" project in Solution Explorer and select "Build". Once built, the DLL file will be generated in the project's bin folder.

Now, let's create a new Console Application (.NET Core) project to reference and use our class library. In Visual Studio, go to File > New > Project, then select ".NET Core" and "Console Application (.NET Core)". Name your project, for example, "ConsoleApp1", and choose a location to save it.

To reference the class library, right-click on the "ConsoleApp1" project in Solution Explorer, select "Add" > "Reference...", then browse and select the "MyClassLibrary" project. Click "OK" to add the reference.

Dewey Decimal System
Dewey Decimal System

Now, let's use the math utility methods in our console application. Open the "Program.cs" file and replace its contents with the following code:

using System;
using MyClassLibrary;

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            int a = 10, b = 5;

            Console.WriteLine($"Addition: {MathUtils.Add(a, b)}");
            Console.WriteLine($"Subtraction: {MathUtils.Subtract(a, b)}");
            Console.WriteLine($"Multiplication: {MathUtils.Multiply(a, b)}");
            Console.WriteLine($"Division: {MathUtils.Divide(a, b)}");

            Console.ReadKey();
        }
    }
}

When you run the console application, it will display the results of the math operations using the methods from our class library.

a book shelf filled with lots of books on top of white shelves next to a stuffed animal
a book shelf filled with lots of books on top of white shelves next to a stuffed animal
Free School Class Library database template for Organizer Advantage - Database Manager for Windows
Free School Class Library database template for Organizer Advantage - Database Manager for Windows
My Classroom Library Organization: A System That Works
My Classroom Library Organization: A System That Works
Classroom Library Labels That Work
Classroom Library Labels That Work
What's a Library Lesson Curriculum Matrix & How Do I Use It? - School Librarians often struggle to c
What's a Library Lesson Curriculum Matrix & How Do I Use It? - School Librarians often struggle to c
a sign up sheet for class library checkout
a sign up sheet for class library checkout
Library Management System ER Diagram 📚 | Complete DBMS ERD for Students & Projects
Library Management System ER Diagram 📚 | Complete DBMS ERD for Students & Projects
12 classroom layouts that are great for students to use in their own class room
12 classroom layouts that are great for students to use in their own class room
3 Strategies for a First-Time School Librarian -Looking Backward with No Sweat Library
3 Strategies for a First-Time School Librarian -Looking Backward with No Sweat Library
the library is full of tables and couches, with many different seating areas on each floor
the library is full of tables and couches, with many different seating areas on each floor
K-5 Elementary Library Curriculum Map
K-5 Elementary Library Curriculum Map
How Simplifying Library Orientations Will Simplify Library Management
How Simplifying Library Orientations Will Simplify Library Management
How to Build a Note Library That Grows With Every Chapter
How to Build a Note Library That Grows With Every Chapter
Classroom Library Ideas: How to build a diversity audit into your classroom library inventory spreadsheet - Inquiring Intermediates
Classroom Library Ideas: How to build a diversity audit into your classroom library inventory spreadsheet - Inquiring Intermediates
The Library Pack
The Library Pack
Effortless Classroom Library Organization system f
Effortless Classroom Library Organization system f
My (FREE) Library Curriculum Map
My (FREE) Library Curriculum Map
c basics
c basics
3 Tools for Library Organization
3 Tools for Library Organization
What Actually Belongs in a First Grade Literacy Block? | Literacy Block Ideas for First Grade
What Actually Belongs in a First Grade Literacy Block? | Literacy Block Ideas for First Grade

Versioning and Packaging Class Libraries

In a real-world scenario, you would want to version and package your class libraries for easy consumption. You can use tools like NuGet to create and publish packages.

Versioning Class Libraries

To version your class library, update the "AssemblyInfo.cs" file in the project. You can change the assembly version number by modifying the "AssemblyVersion" attribute. For example, change it to "1.1.0.0".

Packaging Class Libraries with NuGet

To create a NuGet package, right-click on the "MyClassLibrary" project, select "Pack" > "Create NuGet package". This will generate a NuGet package file (.nupkg) in the project's bin folder.

You can then publish this package to a NuGet feed, such as NuGet.org or a private feed, for others to consume in their projects.

In conclusion, creating and using class libraries in C# is a powerful way to promote code reusability and maintainability. By following the steps outlined in this article, you can create your own class libraries and share them with others. Happy coding!