Namespaces in C # with Examples – C# Programming Example
Class

Namespaces in C # with Examples

Namespaces called namespace are a way of organizing the different types involved in a C # program.

In this tutorial, we will learn about Namespaces, how to define it, access its members, and use it in a C# program with examples.

We can compare the namespace to folders, the behavior is identical to a folder, it is possible to have elements of the same name in different namespace.

The entire framework.net is based on namespaces, it allows above all a good organization and facilitates the search of the elements.

Example, everything about collections will be in System.Collections. All about disk access is in System.IO.

When designing your program, it is strongly recommended to create your own namespace.

 

Create a Namespace

To create your namespace, it is sufficient before each class to specify in which namespace is your code.

 

Use your namespace

To use your namespace, it works like those of the framework. Example with the namespace created above.

Some namespace are very long, to avoid having to write them in full, you can at the beginning of your file in the zone of declaration of the namespace to add some. To add the namespace shortcuts:

This allows you in your code to use the Car and Bike classes directly without specifying the namespace before.

 

Examples 1:

When we run the program, the output will be:

In the above program, we have created our own namespace MyNamespace and accessed its members from Main() method inside MyClass. As said earlier, the dot (.) operator is used to access the member of namespace.

In the Main() method, myMethod() method is called using the dot (.) operator.

Using a Namespace in C# [The using Keyword]

A namespace can be included in a program using the using keyword. The syntax is,

For example,

The advantage of this approach is we don’t have to specify the fully qualified name of the members of that namespace every time we are accessing it.

Once the line

is included at the top of the program. We can write

Instead of the fully qualified name i.e.


Nested Namespace in C#

A namespace can contain another namespace. It is called nested namespace. The nested namespace and its members can also be accessed using the dot (.) operator.

The syntax for creating nested namespace is as follows:


Example 2:

 

When we run the program, the output will be:

This example illustrates how nested namespace can be implemented in C#.

Here, we now have an extra namespace inside MyNamespace called Nested. So, instead of using MyNamespace.SampleClass.myMethod(), we have to use MyNamespace.Nested.SampleClass.myMethod().

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: