C# Namespaces: Definition and Usage

In C#, namespaces are used to organize and manage code for better project structure and to avoid naming conflicts. To define a namespace, you can use the keyword “namespace”, as shown below:

namespace MyNamespace
{
    // 在这里定义类、方法等
}

To use a class or method from a namespace in your code, you can refer to it in the following way:

using MyNamespace;

namespace MyProgram
{
    class Program
    {
        static void Main()
        {
            MyClass myObject = new MyClass();
            myObject.MyMethod();
        }
    }
}

In the example above, we reference the MyClass class and MyMethod method in the MyNamespace namespace within the MyProgram namespace.

Additionally, you can also use aliases to refer to namespaces in order to avoid naming conflicts.

using Alias = MyNamespace.MyClass;
bannerAds