One of the features that was included with C#/VB.NET is the idea of name-spaces, which are not necessarily a requirement to write object-oriented code, however do a a great job of creating a hierarchical class structure and generally keeping your classes, methods, enumerations, etc in non-spaghetti-code state.
What is a namespace?
A namespace can best be described as a collection of classes and enumerations.
Typically, you would want to put classes and enums together in a namespace that are related. For example, if you were considering making some C# code to represent the organization structure of a library, you might have a namespace for the library as a whole, then have sub-namespaces for different aspects of the library, such as the materials that can be rented out in a library, the library’s staff members, and its facilities.
Here’s what a hierarchical structure of namespaces might look like in a Library in C#
You’ll notice that name spaces can be hierarchically organized and that name spaces can contain both classes and enumerations. They can also hold delegates, interfaces and structs. They cannot directly include methods, which must be contained within a class.
Referencing a Class in a Namespace
If you were to create the class that we just made above and put it into a C# application (most likely in the app_code folder), this is how you would create some of the classes above:
AdministrationBuilding – Library.Facilities.AdministrationBuilding thisBuilding = new Library.Facilities.AdministrationBuilding();
Journal – Library.Materials.Periodicals.Journal thisJournal = new Library.Materials.Periodicals.Journal();
BookType – Library.Materials.BookType thisType = new Library.Materials.BookType();
Making Good use of the Using Declaration
If you plan to make use of a namespace a lot on a particular form, web-form, or any other C#/VB file, you can import the namespace directly on the page much in the way that you might import one of the inherited namespaces under the “System” class.
When doing development, if you wanted to create a DataTable object, you would probably want to add “using System.Data;” to the top of your page so that you can reference the variable type by just using “DataTable ThisTable” rather than “System.Data.DataTable ThisTable”.
You can also do this with your own namespaces.
Here’s how you would import the “periodicals” namespace in C# — using Library.Materials.Periodicals;
Here’s how you would import the “periodicals” namespace in VB.NET — Imports Library.Materials.Periodicals
Now, instead of creating a journal like we did above, we could simply write “Journal thisJournal = new Journal();” to create a new object of type Journal.
Here are a few other good resources on Namespaces: