Namespaces in C#
What are Namespaces in C#?
A namespace in C# is a logical container for organizing classes, interfaces, structs, and other types. It helps prevent naming conflicts by grouping related functionalities under a specific name.
Key Features of Namespaces
- Organizes code into logical groups.
- Avoids name conflicts in large projects.
- Allows aliasing for long or conflicting namespaces.
- Supports hierarchical structures for better code organization.
Declaring and Using Namespaces
Namespaces are declared using the namespace
keyword, and they can be used with the using
directive.
Example: Declaring and Using Namespaces
namespace MyNamespace
{
public class Greeting
{
public void SayHello()
{
Console.WriteLine("Hello from MyNamespace!");
}
}
}
// Usage in another file
using MyNamespace;
class Program
{
static void Main()
{
Greeting greet = new Greeting();
greet.SayHello();
}
}
// Output:
// Hello from MyNamespace!
Here, MyNamespace
contains a class Greeting
, which is accessed using the using
directive.
Nested Namespaces
C# supports nested namespaces, allowing hierarchical organization of code.
Example: Nested Namespaces
namespace OuterNamespace
{
namespace InnerNamespace
{
public class Sample
{
public void Display()
{
Console.WriteLine("Inside InnerNamespace");
}
}
}
}
// Usage
using OuterNamespace.InnerNamespace;
class Program
{
static void Main()
{
Sample obj = new Sample();
obj.Display();
}
}
// Output:
// Inside InnerNamespace
The InnerNamespace
is inside OuterNamespace
, making it easier to organize complex projects.
Using Namespace Aliases
Aliases help in resolving naming conflicts or shortening long namespace names.
Example: Namespace Alias
using Sys = System; // Alias for System namespace
class Program
{
static void Main()
{
Sys.Console.WriteLine("Using alias for System namespace!");
}
}
// Output:
// Using alias for System namespace!
The alias Sys
is used to refer to the System
namespace, making code shorter and readable.
Commonly Used Built-in Namespaces
Namespace | Purpose |
---|---|
System |
Provides fundamental types like int , string , Console , etc. |
System.Collections.Generic |
Contains generic collection classes like List and Dictionary . |
System.IO |
Provides file and stream handling functionalities. |
System.Linq |
Provides LINQ capabilities for querying collections. |
System.Threading |
Supports multi-threading and parallel processing. |
Best Practices for Using Namespaces
- Use meaningful namespace names that reflect functionality.
- Follow hierarchical structures to organize large projects.
- Use
using
statements at the top of files to avoid fully qualified names. - Use aliasing when working with conflicting namespaces.
- Keep global namespaces clean and structured.