Search⌘ K
AI Features

Namespaces and Class Libraries

Explore how to use namespaces to organize C# classes and avoid naming conflicts. Understand file-scoped and nested namespaces, and learn how to import and reference class libraries to reuse code effectively across multiple projects.

User-defined classes and structures do not exist in isolation. They are enclosed in containers called namespaces.

When we define a class, we usually place it inside a namespace to organize our code and prevent naming conflicts. The name of this namespace often matches the project name.

C# 14.0
namespace MyFirstProject
{
class Program
{
static void Main(string[] args)
{
}
}
}
  • Line 1: Defines the namespace MyFirstProject.

  • Line 3: Defines the Program class inside the namespace.

  • Line 5: The Main method serves as the entry point of the application.

Defining a namespace

A namespace is defined using the namespace keyword, followed by the name. In the example above, the full name of the Program class is MyFirstProject.Program.

The Program class can access other classes defined in the same namespace without a using directive:

C# 14.0
namespace MyFirstProject
{
class Program
{
static void Main()
{
Employee employee = new Employee();
}
}
class Employee
{
// Employee logic here
}
}
  • Line 1: Declares the namespace MyFirstProject.

  • Line 7: Instantiates the Employee class. Because Employee is in the same namespace, no using directive is required.

  • Line 11: Defines the Employee class within the same namespace block. ...