|
Namespaces are C# program elements that are used for logical grouping of the classes. They also provide assistance in avoiding name clashes between two sets of codes. Namespaces doesn't corresponds to file or directory names. The using directives e.g.
Using System;
This contains number of classes, by including this namespace we can access those classes that are there in the System namespace.
Example:- Demonstrate Namespace

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Test = rootnamespace.firstlevelnamespace;
namespace cSHARPEXAMPLES
{
public partial class Form5 : Form
{
public Form5()
{
InitializeComponent();
}
private void button1_Click( object sender, EventArgs e)
{
rootnamespace.firstlevelnamespace. TestDemo .fxTest();
rootnamespace.firstlevelnamespace. TestDemo11 .fxDisplay();
Test. TestDemo11 .fxDisplay();
}
private void button2_Click( object sender, EventArgs e)
{
secondnamespace.firstlevelnamespace. TestDemo1 .fxTest1();
secondnamespace.firstlevelnamespace. TestDemo1 .fxTest();
}
}
}
namespace rootnamespace
{
namespace firstlevelnamespace
{
class TestDemo
{
public static void fxTest()
{
MessageBox .Show( "Fire UP rootnamespace " );
}
}
class TestDemo11
{
public static void fxDisplay()
{
MessageBox .Show( "Display under rootnamespace " );
}
}
}
}
namespace secondnamespace
{
namespace firstlevelnamespace
{
class TestDemo1
{
public static void fxTest1()
{
MessageBox .Show( "Fire UP secondnamespace" );
}
public static void fxTest()
{
MessageBox .Show( "Fire UP secondnamespace.firstlevelnamespace.fxTest" );
}
}
}
}
Example Explanation:
In above example we have 3 namespaces i.e. cSHARPEXAMPLES, rootnamespace, secondnamespace.Rootnamespace contains irstlevelnamespace namespace,2 classes i.e TestDemo, TestDemo11 and these classes contains methods i.e. fxTest(),fxDisplay(). Secondnamespace contains nested namespace i.e. firstlevelnamespace, 1 class i.e. TestDemo1 and the class contains methods i.e fxTest1(),fxTest(). |