Fremus.co.za

Demistifying Life and Web Development

Understanding namespaces in C# and .NET

Have you ever seen the using statements at the top of your C# source files and wondered how exactly these work? I sometimes simply type them because I understand which classes I need, but if you look at the way a C# class source code is structured it is fairly easy to understand. So lets say I have a random/thought-up class called car and within that vehicle class I have a name space called car, boat, aeroplane. Now imagine that each one of the classes has a class called engine (because the properties and characteristics of engines in all three could be very different), then you would create three namespaces and within each namespace and create a class called engine, and remember all three these namespaces are part of a namespace called Vehicle. So the basic code would look like this:

namespace Vehicle
{
    class Vehicle
    {
    }
    namespace Car
    {
        class Engine
        {
        }
    }
    namespace Boat
    {
        class Engine
        {
        }
    }
    namespace Aeroplane
    {
        class Engine
        {
        }
    }
}

And when you want to re-use those classes in other parts of your program, then you can add:

using Vehicle;

And to instantiate one of the Engine classes you would say:

Aeroplane.Engine aeroplaneEngine = new Aeroplane.Engine();
  • Share/Bookmark
posted by fr3dr1k in C# and have No Comments
Tags:

Place your comment

Please fill your data and comment below.
Name
Email
Website
Your comment
Get Adobe Flash playerPlugin by wpburn.com wordpress themes