Search This Blog

Saturday, November 5, 2011

What is Namespace in asp.net ?

Namespace :-


                          The Namespace is the container of all the classes in c# language same as package in java.


Namespaces are helps us to organize our code in the systematic manner. A namespace is a logical naming scheme for types in which a simple type name, such as MyType, is preceded with a dot-separated hierarchical name.


System is the basic namespace used by every .NET code. If we can explore the System namespace little bit, we can see it has lot of namespace user the system namespace. For example, System.Io, System.Net, System.Collections, System.Threading, etc.




A namespace can be created via the Namespace keyword. Here is an example to create "Books" namespace in VB.NET and C#.
VB.NET Code:

Namespace BooksClass Authors'Do somethingEnd ClassEnd Namespace

C# Code:
namespace Books{class Authors{//Do something}}

This is simple namespace example. We can also build hierarchy of namespace. Here is an example for this.
VB.NET Code:
Namespace BooksNamespace InventoryImports SystemClass AddInventoryPublic Function MyMethod()Console.WriteLine("Adding Inventory via MyMethod!")End FunctionEnd ClassEnd NamespaceEnd Namespace
C# Code:
namespace Books{namespace Inventory{using System;class AddInventory{public void MyMethod(){Console.WriteLine("Adding Inventory via MyMethod!");}}}}
That's all it takes to create namespace. Let's look how we can use the namespaces in our code. I'm going to create a standalone program to use the namespaces.
VB.NET Code:
Imports SystemClass HelloWorldPublic Sub Main()Dim AddInv As Inventory.AddInventory = New AddInventoryAddInv.MyMethod()End SubEnd Class
OR
Imports System.InventoryClass HelloWorldPublic Sub Main()Dim AddInv As AddInventory = New AddInventoryAddInv.MyMethod()End SubEnd Class
C# Code:
using Books;class HelloWorld{public static void Main(){Inventory.AddInventory AddInv = new AddInventory();AddInv.MyMethod();}}
OR
using Books.Inventory;class HelloWorld{public static void Main(){AddInventory AddInv = new AddInventory();AddInv.MyMethod();}}
Note: When using Imports statement or Using statement we can use only the namespace names, we can't use the class names. For example, the following statements are invalid.
Imports Books.Inventory.AddInventory
using Books.Inventory.AddInventory;

1 comment: