Related Posts with Thumbnails

Namespaces

Monday, May 3, 2010

Namespace is a group of related classes. It is a good practice to group related classes into a namespace when you create a class library.

The main advantage of using namespaces is, to avoid conflicts when you have multiple classes with the same name. For example, .NET comes with a class called 'Form'. Suppose you also write another class called 'Form' in your application and if you refer to the class 'Form', how does the compiler know which Form you are refering to ?

Here is the importance of 'namespace'. You can refer to the .NET Form using the fully qualified name, including the namespace like this :

System.Windows.Forms.Form 

And you can refer to your own Form like this :

MyApplication.Form, where MyApplication is your namespace.

So, namespaces allow you to avoid name conflicts!

All classes in .NET class library are grouped into namespaces. You can use all the classes using the fully qualified name, including the namespace also along with the class name.






  • System.Windows.Forms.Form



  • System.String




  • System.Double 

    If you want to declare a Button object, you must do the following :

    System.Windows.Forms.Button myButton;

    It is not mandatory to use the namespace also along with the name. You may use the using directive on top of the class and safely avoid the need to write the fully qualified name everytime when you refer to a class.

    using System.Windows.Forms.Button;

    If you have the above line of code on top of the class file, you don't need to type the namespace name System.Windows.Forms with all the classes in this namespace. You can simply use class name directly as shown below:

    Button myButton;

    .NET Namespaces

    Here is a list of some of the namespaces in .NET class library.






  • System



  • System.Xml



  • System.Data



  • System.Data.OleDb





  • System.Data.SqlClient 
  • 0 comments:

    Post a Comment

    Site Rate