C++: Namespace

This entry is part 4 of 61 in the series C++

A namespace is a declarative region that attaches an identifier to any names declared inside it.

The identifier makes it less likely that a name will conflict with names declared elsewhere in the program.

In the example below, std is a namespace declaration.

#include <iostream>

int main()
{
	std::cout << "Hello World";
	getchar();
}

By using std::cout, we ensure that we are using cout in the namespace std and not elsewhere.

To make our code look cleaner, we can use using namespace.

#include <iostream>
using namespace std;

int main()
{
	cout << "Hello World";
	getchar();
}

 

C#: namespace and class

This entry is part 10 of 71 in the series C#

Using the earlier simple program, we go through the components of a C# program.

using System;

namespace ConsoleHelloApplication
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Hello, World");
            Console.ReadLine();
        }
    }
}

A namespace is a collection of classes.

Here in our simple program, there are actually 2 namespaces namely, System and ConsoleHelloApplication.

For the namespace ConsoleHelloApplication, we have only one class known as Program.

For the namespace System, we have used Console class to print out a line.

In an object-oriented program, we commonly say that Program class is a member of namespace ConsoleHelloApplication.

We can also say that the Main function is a member of Program class.

There is one more class here with 2 member functions.  Are you able to name the 2 member functions?

Well, the class is Console and the 2 member functions are WriteLine() and ReadLine().  The 2 member functions are also called the methods of Console class.