Assemblies are fundamental units of deployment in C# and the .NET framework. They serve as the building blocks for organizing and distributing code, providing a way to package related functionality into a single, reusable unit.
An assembly is a compiled code library used for deployment, versioning, and security. It can be either an executable (.exe) or a dynamic-link library (.dll) file. Assemblies contain compiled code, metadata, and resources that are essential for .NET applications.
Assemblies are typically created when you compile your C# code. The compiler generates an assembly based on your project settings and source files.
// Example: Creating a simple class library assembly
public class MyLibrary
{
public static string GetMessage()
{
return "Hello from MyLibrary assembly!";
}
}
To create this assembly, compile the code using the C# compiler or build it in Visual Studio.
To use an assembly in your C# project, you need to reference it. This can be done through Visual Studio's "Add Reference" feature or by using the command-line compiler.
// Example: Using a referenced assembly
using System;
using MyLibraryNamespace;
class Program
{
static void Main()
{
Console.WriteLine(MyLibrary.GetMessage());
}
}
Every assembly contains a manifest, which is metadata describing the assembly itself. It includes information such as:
Strong-named assemblies provide a way to uniquely identify and verify the integrity of assemblies. They are signed with a public/private key pair and include a digital signature.
To create a strong-named assembly, use the sn.exe
tool to generate a key pair, then use the /keyfile
or /keycontainer
compiler option.
The Global Assembly Cache is a machine-wide cache for storing and sharing assemblies. It allows multiple applications to share common assemblies, reducing duplication and improving performance.
Assemblies are crucial components in C# and .NET development. They provide a modular approach to organizing code, simplify deployment, and enhance security. Understanding how to create, use, and manage assemblies is essential for building robust and maintainable C# applications.
For more information on related topics, explore C# Common Language Runtime and C# Base Class Library.