Curriculum
Namespace in C# is a way to organize related code and avoid naming conflicts between classes, interfaces, enums, and other types in a program. A namespace can contain other namespaces, as well as classes, interfaces, and other types.
Namespace Example:
namespace MyCompany.MyProduct { class MyClass { // class implementation } interface MyInterface { // interface implementation } }
In the example above, we have defined a namespace called “MyCompany.MyProduct” and inside that namespace, we have defined a class called “MyClass” and an interface called “MyInterface”. This helps us to organize our code and avoids naming conflicts with other types in our program.
Namespace Rules:
For example, if we want to use the “MyClass” and “MyInterface” types from the “MyCompany.MyProduct” namespace in another file, we can use the following syntax:
using MyCompany.MyProduct; class AnotherClass { void SomeMethod() { MyClass obj = new MyClass(); MyInterface intf = new MyClass(); } }
In the example above, we have imported the “MyCompany.MyProduct” namespace using the “using” keyword and can now refer to the “MyClass” and “MyInterface” types without having to fully qualify the namespace name each time.
Overall, namespaces are a powerful way to organize and manage code in C#, and understanding their rules is essential for writing clean, maintainable code.