Namespaces and Assemblies in C#
Learn how namespaces and assemblies work in C# to organize code, manage dependencies, and structure projects effectively.
In the C# and .NET world, the concepts of namespace and assembly are used to make code organized, manageable, and reusable. These structures allow code to be modularized, prevent naming conflicts, and make components easy to share, even in large projects.
Namespace
A namespace groups classes, interfaces, enums, and other types under a logical unit. This way, classes with the same name can be used without conflict under different namespaces.
namespace ProjectA.Models
{
class User
{
public string Name { get; set; }
}
}
namespace ProjectB.Models
{
class User
{
public string FullName { get; set; }
}
}
In this example, there are two different User classes.
When namespaces are used, they can be accessed as
ProjectA.Models.User or ProjectB.Models.User.
using Statement
The using statement provides direct access to the types inside a specific namespace.
using ProjectA.Models;
class Program
{
static void Main()
{
User u = new User();
u.Name = "John";
Console.WriteLine(u.Name);
}
}
Here, instead of writing ProjectA.Models.User,
you can simply write User.
Assembly
An assembly is the deployable unit of compiled .NET code.
It usually comes with the extension .dll (Dynamic Link Library) or .exe (executable).
- DLL: Cannot run on its own, referenced by other projects.
- EXE: Executable applications, usually containing an entry point (
Main).
Assembly Contents
An assembly contains not only code but also metadata (e.g., version information) and resource files.
- Manifest: Defines the identity of the assembly (name, version, culture).
- MSIL Code: Compiled intermediate language code.
- Metadata: Information about classes, methods, and properties.
- Resources: Additional files such as images, icons, XML, etc.
TL;DR
- Namespace: Organizes code into logical groups.
- Assembly: Deployable unit of compiled code (.dll, .exe).
- Namespace → prevents naming conflicts and provides structure.
- Assembly → contains code, metadata, and resources in a single package.