แก้ไข

แชร์ผ่าน


Declare namespaces to organize types

Namespaces are heavily used in C# programming in two ways. First, .NET uses namespaces to organize its many classes, as follows:

System.Console.WriteLine("Hello World!");

System is a namespace and Console is a class in that namespace. The using keyword can be used so that the complete name isn't required, as in the following example:

using System;
Console.WriteLine("Hello World!");

For more information, see the using Directive.

Important

The C# templates for .NET 6 use top level statements. Your application may not match the code in this article, if you've already upgraded to the .NET 6. For more information see the article on New C# templates generate top level statements

The .NET 6 SDK also adds a set of implicit global using directives for projects that use the following SDKs:

  • Microsoft.NET.Sdk
  • Microsoft.NET.Sdk.Web
  • Microsoft.NET.Sdk.Worker

These implicit global using directives include the most common namespaces for the project type.

For more information, see the article on Implicit using directives

Second, declaring your own namespaces can help you control the scope of class and method names in larger programming projects. Use the namespace keyword to declare a namespace, as in the following example:

namespace SampleNamespace
{
    class SampleClass
    {
        public void SampleMethod()
        {
            System.Console.WriteLine(
                "SampleMethod inside SampleNamespace");
        }
    }
}

The name of the namespace must be a valid C# identifier name.

Beginning with C# 10, you can declare a namespace for all types defined in that file, as shown in the following example:

namespace SampleNamespace;

class AnotherSampleClass
{
    public void AnotherSampleMethod()
    {
        System.Console.WriteLine(
            "SampleMethod inside SampleNamespace");
    }
}

The advantage of this new syntax is that it's simpler, saving horizontal space and braces. That makes your code easier to read.

Namespaces overview

Namespaces have the following properties:

  • They organize large code projects.
  • They're delimited by using the . operator.
  • The using directive obviates the requirement to specify the name of the namespace for every class.
  • The global namespace is the "root" namespace: global::System will always refer to the .NET System namespace.

C# language specification

For more information, see the Namespaces section of the C# language specification.