I searched many articles to understand the concept of namespace? But I could not understand. Can anyone explain the concept of namespace with simple example? Why do we import namespace?
3 Answers
The following is pseudo-code, I hope it's clear
namespace1.SomeClass
namespace2.SomeClass
var x = new SomeClass(); //which class are we trying to instantiate?
var y = new namespace1.SomeClass(); //now compiler and everyone else knows

- 15,915
- 3
- 48
- 72
A namespace is used to organize objects in categories and control the scope of objects.
More details about .NET namespaces on : http://msdn.microsoft.com/en-us/library/0d941h9d
Notice that the namespace concept is not limited to .NET but to many programming languages.

- 2,989
- 4
- 29
- 34
Why Namespace?
Namespaces are used to organize code. It lets you organize code and gives you a way to create globally unique types and avoid name collisions.
e.g.
Suppose, you have created a class Foo
in your code. In same project, you are using some third party library, in which also a class with same name exists. In this case, when you are referring class Foo
, compiler won't be able to resolve it.
But, this problem can be solved by namespaces. The Foo
class in the library you are using, belongs to some namespace specified by developer of it. (Usually, it contains company name or something unique identifier). And your Foo
class belongs to namespace you have specified. So, at the time of using it, you can specify fully qualified name of the class like <Namespace>.Foo
. Which will make it easy for compiler to resolve reference.
Also, you yourself can categorize your classes using namespace to bifurcate it according to their purpose. Which will be easier to maintain. (e.g. CoreFramework.Foo
, UIHelper.Bar
, etc...)
Why do we import namespace?
Now, at the time using class you have categorized by namespace. You will have to tell compiler in which namespace the referring class contains. By default, compiler looks for the classes in same namespace. If the class you are referring belongs to another namespace, either you will have to specify fully qualified name of the class (i.e. Namespace.Foo
) or you can inform compiler at the beginning of the class by using import statement that, code withing the class contains references to the classes belonging to this namespace.

- 2,674
- 3
- 24
- 33