ScholarQuill logoScholarQuillUniversity Notes
  • Notes
  • Past Papers
  • Blogs
  • Todo
Login
ScholarQuill logoScholarQuillUniversity Notes
Login
NotesPast PapersBlogsTodo
More
SubjectsDiscussionCGPA CalculatorGPA CalculatorStudent PortalCourse Outline
About
About usPrivacy PolicyReportContact
Notes
Past Papers
Blogs
Todo
Analytics
    Current Subject
    🧩
    Advanced Programming
    CSI-415
    Progress0 / 55 topics
    Topics
    1. Visual Programming Basics2. Introduction to Events3. Fundamentals of Event-Driven Programming4. Message Handling5. User Interfaces6. Graphics Device Interface7. Painting and Drawing8. Windows Management9. Input Devices10. Resources11. String and Menu Resource12. Dialogs and Windows Controls13. Common Controls14. Dynamic Link Libraries (DLLs)15. Threads and Synchronization16. Network Programming17. Building Class Libraries at the Command Line18. Class Libraries19. Using References20. Assemblies21. Private Assembly Deployment22. Shared Assembly Deployment23. Configuration Overview24. Configuration Files25. Programmatic Access to Configuration26. Using SDK Tools for Signing and Deployment27. Metadata28. Reflection29. Late Binding30. Directories and Files31. Serialization32. Attributes33. Memory Management and Garbage Collection34. Threading and Synchronization35. Asynchronous Delegates36. Application Domains37. Marshal by Value38. Marshal by Reference39. Authentication and Authorization40. Configuring Security41. Code Access Security42. Code Groups43. Evidence44. Permissions45. Role-Based Security46. Principals and Identities47. Using Data Readers48. Using Data Sets49. Interacting with XML Data50. Tracing Event Logs51. Using the Boolean Switch and Trace Switch Classes52. Print Debugging Information with the Debug Class53. Instrumenting Release Builds with the Trace Class54. Using Listeners55. Implementing Custom Listeners
    CSI-415›Building Class Libraries at the Command Line
    Advanced ProgrammingTopic 17 of 55

    Building Class Libraries at the Command Line

    7 minread
    1,111words
    Intermediatelevel

    Building Class Libraries at the Command Line in C#

    In C#, class libraries are assemblies that contain reusable code, typically in the form of classes, methods, and other types. These libraries can be used across different projects. You can build and compile class libraries from the command line without using an integrated development environment (IDE) like Visual Studio. This can be particularly useful for automation, scripting, or working on lightweight projects.

    This guide will cover the steps to create, build, and reference class libraries using the command line in C#.


    1. Understanding Class Libraries in C#

    A class library is a collection of code organized in a DLL (Dynamic Link Library) or EXE (Executable) file. The classes, methods, and other types in the library can be accessed and used by other programs.

    Key points about class libraries:

    • DLL (Dynamic Link Library) files are the most common type of class libraries.
    • You can write a class library, build it into a DLL, and then reference that DLL in other applications.
    • Class libraries do not have entry points like console applications (no Main method).

    2. Tools Needed

    .NET CLI (Command Line Interface)

    The .NET CLI (dotnet) is a powerful tool provided by Microsoft for building, running, and managing .NET applications from the command line. It allows developers to create, restore, build, run, and publish projects without needing Visual Studio.

    Ensure you have the .NET SDK installed on your system. You can verify this by running:

    dotnet --version
    

    This should display the version of the .NET SDK installed.

    C# Compiler (csc)

    If you're working with .NET Framework instead of .NET Core or .NET 5/6, you can use the C# compiler (csc), which is included in the .NET Framework SDK, to compile class libraries.

    However, the .NET CLI (dotnet) is the recommended approach for modern development.


    3. Creating a Class Library Using .NET CLI

    Step 1: Create a Class Library Project

    To create a class library in C# using the .NET CLI, follow these steps:

    1. Open a terminal or command prompt.
    2. Create a new directory for your class library (optional).
    3. Use the dotnet new command to create a new class library project.
    dotnet new classlib -n MyClassLibrary
    
    • dotnet new classlib: Creates a new class library project.
    • -n MyClassLibrary: Specifies the name of the project.

    This will create a folder named MyClassLibrary with the following default structure:

    MyClassLibrary
    │   MyClassLibrary.csproj
    │   Class1.cs
    └───obj
    └───bin
    

    The MyClassLibrary.csproj file is the project file, and Class1.cs is a sample class file.

    Step 2: Write Your Class Library Code

    Navigate to the Class1.cs file, and you can define your custom classes. For example:

    namespace MyClassLibrary
    {
        public class MyClass
        {
            public string SayHello()
            {
                return "Hello from MyClassLibrary!";
            }
        }
    }
    

    This is a simple class that has a SayHello() method.

    Step 3: Build the Class Library

    To build the class library, navigate to the project directory (if not already there) and run the following command:

    dotnet build
    

    This will compile the class library and generate the DLL file. The output will typically be in the bin/Debug/netstandard2.0/ directory (or the appropriate version folder, like net5.0 or net6.0).

    You should see a file like MyClassLibrary.dll in the output directory.


    4. Using the Class Library in Another Project

    To use your class library in another project, you can reference the generated DLL or include the class library as a dependency in another project.

    Option 1: Reference the DLL Directly

    You can directly reference the generated MyClassLibrary.dll in another project. To do this:

    1. Create a new Console Application project:
    dotnet new console -n MyConsoleApp
    
    1. In the MyConsoleApp directory, edit the .csproj file to add a reference to the class library:
    <Project Sdk="Microsoft.NET.Sdk">
    
      <PropertyGroup>
        <OutputType>Exe</OutputType>
        <TargetFramework>net6.0</TargetFramework>
      </PropertyGroup>
    
      <ItemGroup>
        <Reference Include="..\MyClassLibrary\bin\Debug\net6.0\MyClassLibrary.dll" />
      </ItemGroup>
    
    </Project>
    
    • Update the path to match the location of your generated MyClassLibrary.dll.
    1. In your Program.cs file, you can now use the class library:
    using MyClassLibrary;
    
    class Program
    {
        static void Main()
        {
            var myClass = new MyClass();
            Console.WriteLine(myClass.SayHello());
        }
    }
    
    1. Run the application:
    dotnet run
    

    This should display the message from the SayHello() method in your class library.

    Option 2: Add a Project Reference

    Instead of referencing the DLL directly, you can add a project reference to the class library, making it easier to manage and build.

    1. In your MyConsoleApp directory, run:
    dotnet add reference ../MyClassLibrary/MyClassLibrary.csproj
    

    This command adds a reference to the MyClassLibrary project directly, so the DLL is built automatically along with your application.

    1. After adding the reference, you can use the class library in your console app as shown in Step 3.

    5. Building and Packaging the Class Library

    Once you have developed your class library, you may want to distribute it as a NuGet package or just ensure it's built correctly for production.

    Building with Release Configuration

    To build the class library in Release configuration (optimized for production), use the following command:

    dotnet build --configuration Release
    

    This will place the compiled DLL in the bin/Release/net6.0/ directory.

    Publishing the Class Library (Optional)

    You can also publish the class library to a NuGet feed or store it in a local directory.

    1. To publish a package to a local directory, use:
    dotnet pack --configuration Release --output ./nupkgs
    

    This command will package the class library as a .nupkg file in the nupkgs folder.

    1. To publish to NuGet.org, you'll need to create a NuGet API key and configure the feed. You can then run:
    dotnet nuget push ./nupkgs/MyClassLibrary.1.0.0.nupkg --api-key <your-api-key> --source https://api.nuget.org/v3/index.json
    

    6. Summary of Commands

    Here’s a summary of the key commands used when building and managing class libraries from the command line in C#:

    1. Create a new class library:

      dotnet new classlib -n MyClassLibrary
      
    2. Build the class library:

      dotnet build
      
    3. Run the class library (in a consuming app):

      dotnet run
      
    4. Add a project reference:

      dotnet add reference <path-to-class-library>
      
    5. Build in Release mode:

      dotnet build --configuration Release
      
    6. Create a NuGet package:

      dotnet pack --configuration Release --output ./nupkgs
      
    7. Publish the NuGet package:

      dotnet nuget push ./nupkgs/MyClassLibrary.1.0.0.nupkg --api-key <your-api-key> --source https://api.nuget.org/v3/index.json
      

    Conclusion

    Building class libraries from the command line in C# is a straightforward process using the .NET CLI. You can create, build, and manage class libraries effectively without the need for a full-fledged IDE like Visual Studio. This approach is ideal for automation, continuous integration, and lightweight development scenarios. The flexibility of the .NET CLI allows you to integrate class libraries into larger projects or distribute them as packages.

    Previous topic 16
    Network Programming
    Next topic 18
    Class Libraries

    Past Papers

    Open this section to load past papers

    Click on Show Past Papers to see past papers.
    On This Page
      Reading Stats
      Est. reading time7 min
      Word count1,111
      Code examples0
      DifficultyIntermediate