views:

42

answers:

3

Hello I am new to asp.net. I am confused what is the difference between "using MyNameSpace;" and "namespace MyNameSpace". My demo code is as follow...

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

using MyNameSpace;

namespace MyNameSpace

{
    public partial class DemoPage : System.Web.UI.Page
    {
        My code here
    }
}

In the above code is there any difference between the two highlighted statements or not. If yes then what is it?

Thanks in advance...

+4  A: 

Yes, they provide complementary services.

A using directive like this:

using MyNamespace;

Tells the compiler to look in the namespace MyNamespace when resolving simple names - so if you have a type called MyNamespace.Foo, you can just use Foo in your source to refer to it when you've got this using directive.

However, the namespace declaration effectively says, "Anything I declare within this block is in the given namespace". So to declare the MyNamespace.Foo type, you'd use:

namespace MyNamespace
{
    public class Foo
    {
        ...
    }
}

Do you see? The using directive says that you want to use things in a particular namespace, whereas the namespace declaration is about putting things into a particular namespace.

Jon Skeet
Thanks Jon for the nice explanation. I got it now.
Amit
A: 

using is used for creating a "shortcut" to typenames within that namespace. This is only needed when the code you write is within another namespace. namespace is used for defining a namespace:

Example
In file first.cs:

// define the namespace "SomeNamespace"
namespace SomeNamespace
{
    // define a type within the namespace
    class SomeClass { }
}

In file second.cs:

using SomeNamespace;
// define the namespace "OtherNamespace"
namespace OtherNamespace
{
    class OtherClass
    {
        void SomeMethod()
        {
            // use the type "SomeClass", defined in the "SomeNamespace" namespace
            // note that without the using directive above we would need to write
            // SomeNamespace.SomeClass for this to work.
            SomeClass temp = new SomeClass();
        }
    }
}

In the above code sample, the declaration of the temp variable does not need to include the namespace, since it is mentioned in a using directive.

Fredrik Mörk
A: 

Yes, there is a difference. The namespace statement is used to create a namespace, while the using statement is used to make the compiler regognise an already existing namespace.

In your code the using statement has no effect, as all your code is in that namespace so it already knows about it.

As you have using System.Web.UI, the System.Web.UI.Page identifier could be written as just Page as the compiler knows about the classes in that namespace. If you wouldn't have that using statement, you would need the fully qualified name for the compiler to know where to find the class.

Guffa