Namespaces in C#

Mannan Ul Haq
0
A namespace is a way to group related code together in C#. Think of it as a box where you can store all kinds of related things together, whether they're classes, structures, interfaces, or even other namespaces.

Namespaces serve two primary purposes:
  1. Namespaces provide a way to group related classes.
  2. They offer a way to avoid name collisions between multiple classes that might have the same name but are part of different libraries or namespaces.

For example, let's say you're making a video game and you have a bunch of classes that deal with player information. You might put all these classes in a namespace called `PlayerInfo` to keep things neat and organized.

Here's what a namespace looks like in C#:

namespace PlayerInfo
{
    class Player
    {
        // Class content here.
    }
}

In this code, we have a namespace called `PlayerInfo` and inside that namespace, we have a class named `Player`.

Accessing Namespaced Types:

To use a class or other type from a namespace, you need to use its fully qualified name. This is just a fancy way of saying "the namespace name, followed by a dot, followed by the class name".

For example, let's say you want to create a new `Player` object. You could do that like this:

PlayerInfo.Player newPlayer = new PlayerInfo.Player();

In this code, `PlayerInfo.Player` is the fully qualified name of the `Player` class.

Using the `using` Keyword:

The using keyword in C# is used to include namespaces in a program. A program generally has multiple using statements to import different namespaces.

using System;

This statement allows the program to use types in the System namespace without specifying the namespace. For example, you can use 'Console.WriteLine', instead of 'System.Console.WriteLine'.

Example:

// Now we can just write Player instead of PlayerInfo.Player
Player newPlayer = new Player();

With this `using` statement at the top, you can just write `Player` whenever you want to refer to the `Player` class. C# knows you mean `PlayerInfo.Player`.

Tags

Post a Comment

0Comments

Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Check Now
Accept !