A namespace is a declarative region for a code block in order to create scope. The namespace is used to organize the code is an elegant and easily readable way.
Namespace Usecases
Namespaces can be used for different cases.
Creating New Scope
is the most popular use case for the namespaces. Each namespace is a different scope that does not share with other namespaces unless explicitly defined.
Organize Code
is another use case where complex projects, applications, and libraries can be categorized and organized properly. This organization can be done according to functions, groups or modules.
Provide Limited Accessability
is useful for providing namespaces in library for application developers. By using namespaces access to the variables, methods and classes are limited.
Creating and Using Namespace in C++
C++ uses keyword namespace
in order to create a namespace. Namespaces also named in order to access from other scopes or namespaces. All class, methods, variables are put into the specified namespaces. Below we will create a namespace named Poftut
and a class named Manager
.
namespace Poftut
{
class Manager
{
public:
void DoSomething() {}
};
void Func(ObjectManager) {}
}
Below we will use the previously defined namespace Poftut below and create an instance of the class Manager.
using namespace Poftut
Manager mgr;
mgr.DoSomething();
Creating and Using Namespace in PHP
PHP is another programming language that supports namespaces. The namespace support came to the PHP with version 5.3. Namespaces generally defined as source code file wide and namespace
keyword is used to define.
<?php
namespace MyProject;
class Connection{
function connect(){}
}
function test();
?>
In order to use a namespace first, we will import the PHP file which is file1.php
in this example. Then simply we will use the defined namespace name and function, class or variable like below. In the following example, we will create an instance of Connection
class and call the method test()
.
<?php
namespace OtherProject;
include 'file1.php';
$mycon = new MyProject\Connection();
MyProject::test();
?>
Creating and Using Namespace in C#
C# is another programming language that provides namespaces in a very advanced way. Also, C# language, projects, libraries use namespaces heavily. We can create a namespace by using keyword namespace
below and put classes, methods, and variables.
namespace MyProject
{
class MyClass
{
public void MyMehtod()
{
System.Console.WriteLine(
"SampleMethod inside SampleNamespace");
}
}
}
We will use the MyProject
namespace below example and initialize an object and use MyMethod
. In order to use a namespace in C# keyword using
is used.
using MyProject;
namespace OtherProject
{
class OtherClass
{
static void Main()
{
MyProject.MyClass mc = new MyProject.MyClass();
mc.MyMehtod();
}
}
}