Understanding Namespaces

Understanding Namespaces

In C#, a namespace is used to group related classes, interfaces, structures, enumerations, and delegates. It provides a way to organize code and prevent naming conflicts. A namespace can contain other namespaces, as well as classes and other types.

When you create a new C# project, Visual Studio automatically generates a default namespace for it based on the project name. You can also define your own namespace for a class or a group of classes.

To define a namespace, you use the namespace keyword followed by the name of the namespace. For example:

namespace MyNamespace

{

    // classes, interfaces, etc. go here

}

To use a class or other type from a namespace in your code, you can either fully qualify the type name with the namespace:

MyNamespace.MyClass obj = new MyNamespace.MyClass();

Or you can include a using directive at the top of your file to tell the compiler which namespace to look in for a particular type:

using MyNamespace;

MyClass obj = new MyClass();

It is also possible to create nested namespaces to further organize your code. For example:

namespace MyNamespace

{

    namespace SubNamespace

    {

        // classes, interfaces, etc. go here

    }

}

In this case, you would fully qualify a type in the SubNamespace like this:

MyNamespace.SubNamespace.MyClass obj = new MyNamespace.SubNamespace.MyClass();

Or you could add a using directive for the SubNamespace to simplify the code:

using MyNamespace.SubNamespace;

MyClass obj = new MyClass();

The .NET system (on which ASP.NET is based) is thousands of useful chunks of code organized into categories called namespaces. For example, in the code for the Page Load event, you see this line:

System.Drawing.KnownColor enClr;

The namespace used in the preceding code is System.Drawing. The Web server’s hard drive has a system.drawing.dll file, which is where the System.Drawing code resides. In geekspeak, system.drawing.dll is known as an assembly. Within this namespace is a list of system-defined colors, such as YellowGreen.

Retrieving a list of colors

When the page loads the first time, you declare the variable enClr as a KnownColor type. Next, you create a generic list that works easily with ASP.NET controls. You stuff the color values into the list. Finally, you instruct the DropDownList control to get its data from the list. When you fill the DropDownList with data, the control automatically retains the values. Therefore, you fill the data on the initial page load, not on each postback.

Apply for ASP.NET Certification Now!!

https://www.vskills.in/certification/certified-aspnet-programmer

Back to Tutorial

Using the DropDownList Control
Displaying The Color Name and Showing The Color

Get industry recognized certification – Contact us

keyboard_arrow_up
Open chat
Need help?
Hello 👋
Can we help you?