Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 6

Introduction To Namespaces:

Microsofts Visual Studio .NET has introduced many new concepts to the Visual Studio
developer, including the Microsoft Intermediate Language (MSIL) with runtime compilation,
garbage collection, Common Language Runtime (CLR), and, perhaps most misunderstood of all:
namespaces and assemblies. To help you develop a better understanding of the .NET
environment, this article will explore namespaces and assemblies and clarify the relationship
between them.
The namespace
At first glance, it appears as if namespaces represent little more than the C++ include directive or
the addition of a VB module to a project. But the concept of namespaces and assemblies with
the C# using directive and the VB Imports statement in Visual Studio .NET extends beyond the
inclusion of predefined header files. They represent a method of interacting with external code
libraries that may be new to the Microsoft developer.
Put simply, a namespace is just a grouping of related classes. It's a method of putting classes
inside a container so that they can be clearly distinguished from other classes with the same
name. Programmers skilled in the Java language will recognize namespaces as packages. A
namespace is a logical grouping rather than a physical grouping. The physical grouping is
accomplished by an assembly, which equates most directly to a dynamic link library (DLL), COM
object, or OCX module.
The .NET CLR consists of multiple namespaces, which are spread across many assemblies. For
example, ADO.NET is the set of classes located in the System.Data namespace, and ASP.NET
is the set of classes located in the System.Web namespace.
Figure A shows how classes are divided up in the namespaces that compose the .NET CLR.
Each block represents a separate namespace. In the CLR, the classes and structures contained
in each of the namespaces represent a common theme of development responsibility. Further,
the namespace system can be hierarchical, allowing for compartmentalization of functionality
inside of a parent namespace. For example, the System namespace is the root for all other
namespaces.
Figure A

Namespace Implementation
Namespaces in C# is a method designed for organising classes.Other than classes the
namespace can have

Structures

Interfaces

Enumerations

Delegates

A namespace is similar to a package in Java, whereas Java package names represent


directory structure, while C# namespaces represent only the logical structure. They also
help in avoiding clashes between similar named files. Namespace act as boundary
between these two files.Suppose a piece of code using two of them, how could you
differetiate between two? ofcourse the Namespace is the answer.Implementing
Namespaces in your own code is a good practise since one could use the same name of
the classes knowingly or unknowingly without getting into any trouble. using
Namespace allow you to use members of the namespace.
Using Namespace
Namespaces are referenced by C# applications by using the using keyword. For instance,
Using System.Collections.Generic;
System namespace gives access to the interfaces and classes that define generic
collections.Interface such as IList allow one to override its method Add.The Syntax of
Add:
void Add(
)

T item

The Using Directive


Example. DirectiveEx.cs

using System;
using DotNetproject.CSharp;
class DirectiveEx
{
public static void Main()
{
PrintText.textString();
}
}
namespace DotNetproject.CSharp;
{
class PrintText
{
public static void textString()
{
Console.WriteLine("Example Demonstrating Namespace");
}
}
}
The using directive DotNetproject.CSharp allows us to call members of
the DotNetproject.CSharp namespace without using the fully qualified name. This enable
us to callPrintText.textString() directly. Otherwise, whenever we want to call that
method textString we need to write long fully qualified
nameDotNetproject.CSharp.PrintText.textString().

Using Keyword:
The using keyword provides a convenience mechanism to correctly use IDisposable
objects. As a rule, when you use an IDisposable object, you should declare and
instantiate it in a using statement. The using statement calls the Dispose method on the
object in the correct way, and (when you use it as shown earlier) it also causes the
object itself to go out of scope as soon as Dispose is called. Within the using block, the
object is read-only and cannot be modified or reassigned.
The following example shows how to use the using statement.
C#
using (Font font1 = new Font("Arial", 10.0f))
{
byte charset = font1.GdiCharSet;
}
Remarks
File and Font are examples of managed types that access unmanaged resources (in this
case file handles and device contexts). There are many other kinds of unmanaged
resources and class library types that encapsulate them. All such types must implement
the IDisposable interface.

As a rule, when you use an IDisposable object, you should declare and instantiate it in
a using statement. The using statement calls the Dispose method on the object in the
correct way, and (when you use it as shown earlier) it also causes the object itself to go
out of scope as soon as Dispose is called. Within the using block, the object is read-only
and cannot be modified or reassigned.
The using statement ensures that Dispose is called even if an exception occurs while
you are calling methods on the object. You can achieve the same result by putting the
object inside a try block and then calling Dispose in a finally block; in fact, this is how
the using statement is translated by the compiler. The code example earlier expands to
the following code at compile time (note the extra curly braces to create the limited
scope for the object):
C#
{
Font font1 = new Font("Arial", 10.0f);
try
{
byte charset = font1.GdiCharSet;
}
finally
{
if (font1 != null)
((IDisposable)font1).Dispose();
}
}
Multiple instances of a type can be declared in a using statement, as shown in the
following example.
C#
using (Font font3 = new Font("Arial", 10.0f),
font4 = new Font("Arial", 10.0f))
{
// Use font3 and font4.
}
You can instantiate the resource object and then pass the variable to
the using statement, but this is not a best practice. In this case, the object remains in
scope after control leaves the using block even though it will probably no longer have
access to its unmanaged resources. In other words, it will no longer be fully initialized. If
you try to use the object outside the using block, you risk causing an exception to be
thrown. For this reason, it is generally better to instantiate the object in
the using statement and limit its scope to the using block.
C#
Font font2 = new Font("Arial", 10.0f);
using (font2) // not recommended
{
// use font2
}
// font2 is still in scope
// but the method call throws an exception
float f = font2.GetHeight();

Namespace Alias:

The Namespace Alias Qualifier in C# lets developers use the alias name instead of the
complete namespace name. The advantage of the Namespace Alias Qualifier is that it
lets you use the alias name instead of a bigger namespace ( like Inner Namespaces )
and it also helps to avoid the ambiguous definitions of the classes.
For example
Take the below class as an example
view source
print?
01.using System;
02.using System.Collections.Generic;
03.using System.Linq;
04.using System.Text;
05.using System.Threading.Tasks;
06.
07.namespace Namespace1
08.{
09.class Student
10.{
11.public string StudentName { get; set; }
12.}
13.}
14.namespace Namespace2
15.{
16.class Student
17.{
18.public string StudentName { get; set; }
19.}
20.}
When both Namespace1 and Namespace2 are referenced in the C# file and are trying to
create an instance of Student, it will cause the Ambiguous(Samename ) error.
Global Name Alias:
1.

namespace TestModule

2.

3.

class TestClass

4.

5.

class TestModule { }

6.

TestModule.TestClass test = new TestModule.TestClass();

7.
8.

}
}

When you try to instantiate TestClass qualified with the namespace name TestModule,
the compiler will give an error saying: The type name TestClass does not exist in the
type TestModule.TestClass.TestModule. This happens because the class TestModule
which is inside hides the namespace TestModule which is at the global level.

The external alias global(C#)/Global(VB.NET) can be used to resolve conflicts between


namespaces and hiding inner types as shown below:
view plain
1.

namespace TestModule

2.

3.

class TestClass

4.

5.

class TestModule { }

6.

global::TestModule.TestClass test = new global::TestModule.TestClass();

7.
8.

}
}

When the global alias is used, the search for the right-side identifier starts at the
global namespace which is the root level of the namespace hierarchy. This helps to
resolve the type from the outer most level (global level) drilling inwards.

The chances for such conflicts can be avoided to a good extent by following proper
naming standards. But when huge class libraries and third-party components are used
this situation can arise. In such cases the usage of namespace alias qualifier can save a
lot of time!!

You might also like