Letβs go through namespace in C# β a fundamental feature for organizing code.
π 1. What Is a Namespace?
-
A namespace is a logical container for classes, structs, enums, delegates, interfaces, and other types.
-
It prevents name collisions by grouping related types together.
-
Think of it as a folder structure for your code, but at the type level.
π 2. Declaring a Namespace
Basic Syntax
namespace MyApplication
{
class Program
{
static void Main()
{
Console.WriteLine("Hello from MyApplication namespace!");
}
}
class Helper
{
public void DoWork()
{
Console.WriteLine("Working...");
}
}
}- Here, both
ProgramandHelperbelong to theMyApplicationnamespace.
π 3. Nested Namespaces
- Namespaces can be nested to further organize types.
namespace MyApplication.Utilities
{
class Logger
{
public void Log(string message) => Console.WriteLine(message);
}
}
namespace MyApplication.Models
{
class User
{
public string Name { get; set; }
}
}MyApplication.Utilities.LoggerandMyApplication.Models.Userare fully qualified names.
π 4. Using Namespaces
- To use a type from another namespace, you use the
usingdirective:
using MyApplication.Utilities;
class Program
{
static void Main()
{
Logger log = new Logger();
log.Log("Hello!");
}
}- Without
using, you must use the fully qualified name:
class Program
{
static void Main()
{
MyApplication.Utilities.Logger log = new MyApplication.Utilities.Logger();
log.Log("Hello!");
}
}π 5. Key Points
| Feature | Notes |
|---|---|
namespace | Groups related types logically |
| Fully qualified names | Include all parent namespaces (e.g., MyApplication.Utilities.Logger) |
| Prevents naming conflicts | Two classes with the same name in different namespaces are allowed |
| Can be nested | Helps organize large projects |
Used with using | Simplifies code by avoiding full names |
π 6. Analogy
-
Namespace = a folder on your computer.
-
Class inside namespace = a file inside the folder.
-
Multiple folders can have files with the same name without conflict β same with namespaces and classes.
β Summary:
-
Use
namespaceto organize code and avoid name collisions. -
Combine with
usingfor convenience. -
Nested namespaces help structure large projects.