404 Not Found

404 Not Found


nginx

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

CSHARP
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";
        }
    }
}
▶ Try it Yourself

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

CSHARP
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; }
    }
}
▶ Try it Yourself

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

CSHARP
namespace MyApp.Services;

public class EmailService
{
    public void Send(string to)
    {
        System.Console.WriteLine($"Sending email to {to}");
    }
}
▶ Try it Yourself
TEXT
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

CSHARP
using System;

namespace MyApp
{
    class Program
    {
        static void Main()
        {
            Console.WriteLine("No need for System.Console");
            Console.WriteLine(DateTime.Now.Year);
        }
    }
}
▶ Try it Yourself
TEXT
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

CSHARP
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());
        }
    }
}
▶ Try it Yourself
TEXT
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

CSHARP
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)}");
        }
    }
}
▶ Try it Yourself
TEXT
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

CSHARP
global using System;
global using System.Collections.Generic;
global using System.Linq;
▶ Try it Yourself

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

XML
<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net6.0</TargetFramework>
    <ImplicitUsings>enable</ImplicitUsings>
  </PropertyGroup>
</Project>
▶ Try it Yourself

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

CSHARP
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());
        }
    }
}
▶ Try it Yourself
TEXT
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

CSHARP
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());
        }
    }
}
▶ Try it Yourself
TEXT
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

Q Are namespaces and assemblies (DLLs) the same concept?
A No. Namespaces are logical organization; assemblies are physical deployment. One assembly can contain multiple namespaces, and one namespace can span multiple assemblies.
Q Does the using directive increase program size?
A No. using is just compile-time syntactic sugar for simplified notation and has no effect on runtime or program size.
Q Can you nest sub-namespaces inside a file-scoped namespace?
A Yes, you can define sub-namespaces with curly braces inside a file-scoped namespace.
Q What is the difference between global using and ImplicitUsings?
A global using is manually declared by the developer; ImplicitUsings is a set of global usings auto-generated by the SDK, which relies on the global using mechanism.
Q Can using static import instance members?
A No, using static only imports static members and nested types. Instance members still need to be called through an object.

📖 Summary

📝 Exercises

  1. Create a Teacher class in a two-level nested namespace School.Teachers, and instantiate it in Main
  2. Use a using alias to create a short alias for System.Collections.Generic.List<string>, then use it to create a list, add elements, and output them
  3. Use using static System.Math to directly call Sqrt, Abs, and Round, and output the results
  4. Create a GlobalUsings.cs file with global using declarations for System, System.IO, and System.Linq, then omit these usings in another file to verify they work
  5. Use both the curly-brace using statement and using var declaration approaches to write to a file with StreamWriter, and observe the difference
Web-Tutorial.com

Web-Tutorial Tech Team

A team of developers maintaining programming tutorials. Each tutorial is written and reviewed by developers with expertise in that field. We work to keep our content accurate and reliable — if you spot an issue, please let us know.

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏