Namespaces and using
What Is a Namespace
A namespace is a logical grouping mechanism used to organize code and avoid type name conflicts. In large projects, different modules may define classes with the same name; namespaces provide a qualified path for types.
namespace Definition
Use the namespace keyword to declare a namespace, with types placed inside curly braces.
Example
namespace MyApp.Models
{
public class User
{
public string Name { get; set; }
public int Age { get; set; }
}
}
namespace MyApp.Services
{
public class UserService
{
public string GetInfo()
{
return "UserService is ready";
}
}
}
Namespace Nesting
Namespaces can be nested, where inner namespaces are sub-spaces of outer ones. Dot notation access is equivalent to the nested structure.
Example
namespace Company
{
namespace Products
{
namespace Electronics
{
public class Phone
{
public string Model { get; set; }
}
}
}
}
namespace Company.Products.Electronics
{
public class Tablet
{
public string Model { get; set; }
}
}
Company.Products.Electronics.Phone and Company.Products.Electronics.Tablet belong to the same namespace.
File-Scoped Namespaces (C# 10)
C# 10 introduced file-scoped namespaces, which use a semicolon at the end. The entire file automatically resides in that namespace, reducing nesting indentation.
Example
namespace MyApp.Services;
public class EmailService
{
public void Send(string to)
{
System.Console.WriteLine($"Sending email to {to}");
}
}
Sending email to user@example.com
using Directive
The using directive imports a namespace so you can use its types directly without writing the fully qualified name.
Example
using System;
namespace MyApp
{
class Program
{
static void Main()
{
Console.WriteLine("No need for System.Console");
Console.WriteLine(DateTime.Now.Year);
}
}
}
No need for System.Console
2026
using Alias
When a namespace is too long or there are type name conflicts, you can use using ... = ... to create an alias.
Example
using Dict = System.Collections.Generic.Dictionary<string, int>;
using StringBuilder = System.Text.StringBuilder;
namespace MyApp
{
class Program
{
static void Main()
{
Dict scores = new Dict();
scores.Add("Alice", 95);
scores.Add("Bob", 87);
StringBuilder sb = new StringBuilder();
foreach (var pair in scores)
{
sb.AppendLine($"{pair.Key}: {pair.Value}");
}
System.Console.WriteLine(sb.ToString());
}
}
}
Alice: 95
Bob: 87
using static (C# 6)
using static imports the static members of a type, allowing you to call them without the type name.
Example
using static System.Console;
using static System.Math;
namespace MyApp
{
class Program
{
static void Main()
{
WriteLine($"PI = {PI}");
WriteLine($"Max = {Max(10, 20)}");
WriteLine($"Sqrt(144) = {Sqrt(144)}");
}
}
}
PI = 3.14159265358979
Max = 20
Sqrt(144) = 12
Global using (C# 10)
global using declared in one file makes the namespace available across all files in the entire project, eliminating the need to repeat using.
Example
global using System;
global using System.Collections.Generic;
global using System.Linq;
It is common practice to place global usings in a GlobalUsings.cs file for centralized management.
Implicit Usings (C# 10)
Enabling <ImplicitUsings>enable</ImplicitUsings> in the project file causes SDK-style projects to automatically add global usings for commonly used namespaces.
Example
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net6.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
</Project>
Console projects automatically include these namespaces: System, System.Collections.Generic, System.IO, System.Linq, System.Threading, System.Threading.Tasks, etc.
using and IDisposable
The using statement ensures that IDisposable objects properly release resources after use. C# 8 also supports the using declaration syntax.
Example
using System;
using System.IO;
namespace MyApp
{
class Program
{
static void Main()
{
using (var fs = new FileStream("test.txt", FileMode.Create))
{
byte[] data = System.Text.Encoding.UTF8.GetBytes("Hello");
fs.Write(data, 0, data.Length);
}
using var reader = new StreamReader("test.txt");
Console.WriteLine(reader.ReadToEnd());
}
}
}
Hello
The curly-brace form releases at the end of its scope; using var releases at the end of the enclosing scope.
.NET Class Library Namespace Organization
The .NET class library organizes functionality into sub-namespaces under the System namespace.
Example
using System;
using System.IO;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace MyApp
{
class Program
{
static void Main()
{
ArrayList list = new ArrayList { 1, 2, 3 };
List<string> names = new List<string> { "Alice", "Bob" };
var upper = names.Select(n => n.ToUpper());
StringBuilder sb = new StringBuilder("Count: ");
sb.Append(names.Count);
Console.WriteLine(sb.ToString());
}
}
}
Count: 2
| Namespace | Purpose |
|---|---|
System |
Base types (Console, DateTime, Math, etc.) |
System.IO |
File and stream operations |
System.Collections |
Non-generic collections (ArrayList, Hashtable) |
System.Collections.Generic |
Generic collections (List<T>, Dictionary<K,V>) |
System.Linq |
LINQ query extensions |
System.Text |
String processing (StringBuilder, Encoding) |
System.Threading |
Threading and synchronization |
System.Threading.Tasks |
Asynchronous programming (Task, Task<T>) |
❓ FAQ
📖 Summary
- Namespaces are defined with
namespace, supporting curly-brace nesting and dot notation - The
usingdirective imports a namespace, eliminating fully qualified names using Alias = FullTypeNameresolves name conflicts or simplifies long namesusing staticimports a type's static members for direct callingglobal usingis project-wide, avoiding repetition in each file- File-scoped namespace
namespace X;reduces indentation levels - Implicit usings automatically include common namespaces via project configuration
usingstatements/declarations are for IDisposable resource release- .NET class library is divided into System sub-namespaces by functionality
📝 Exercises
- Create a
Teacherclass in a two-level nested namespaceSchool.Teachers, and instantiate it inMain - Use a
usingalias to create a short alias forSystem.Collections.Generic.List<string>, then use it to create a list, add elements, and output them - Use
using static System.Mathto directly callSqrt,Abs, andRound, and output the results - Create a
GlobalUsings.csfile withglobal usingdeclarations forSystem,System.IO, andSystem.Linq, then omit these usings in another file to verify they work - Use both the curly-brace
usingstatement andusing vardeclaration approaches to write to a file withStreamWriter, and observe the difference



