views:

185

answers:

6

Scenario:

Assume I want to define my own class.

public class Person
{
}

I wish to put it in a namespace System.

Note: I have not included the directive, 'using System' at the top..

namespace System
{
    public class Person
    {
        public void Display()
        {
            Console.WriteLine("I am mine");
        }
    }
}

Though I have not included using System; directive at the top, I am still able to access System.Console.WriteLine in my method, since my declared namespace is System.

How is this possible? how does it go about?

A: 

Anything declared inside a namespace has access to all the other classes in that same namespace (provided you have a reference to the assembly containing that namespace and those classes).

jerryjvl
A: 

Namespaces implicitly have public access and this is not modifiable.

Si
A: 

This is because you have declared your class as being part of the namespace and therefore it automatically includes the assembly for it.

In the same way any file within a project namespace doesn't need to declare it as using that project namespace.

ChrisBD
+8  A: 

If you declare namespace Foo.Bar.Baz, every namespace in that hierarchy (Foo, Foo.Bar and Foo.Bar.Baz) is searched when you reference a type from within that namespace declaration:

namespace Foo.Bar.Baz
{
    class Test
    {
        static void Main()
        {
            // This will search for Foo.Bar.Baz.SomeType,
            // Foo.Bar.SomeType, Foo.SomeType, SomeType,
            // in that order
            SomeType.StaticMethod();
        }
    }
}

See section 3.8 of the C# 3.0 language specification for the gory details.

However, I hope you are not seriously considering using this as a way to avoid adding using directives. Creating your own types in the System namespace hierarchy is a very bad idea.

Jon Skeet
+1  A: 

You don't need the using directive inside the same namespace.

If you declare your classes in System then "using System;" is implicit.

However, this is probably not where you should be putting your classes.

Struan
+1  A: 

Because you have defined your type in the System namespace, you have access to all other types defined in the System namespace.

Similarly, if you defined your class in System.Data, you would have access to System and System.Data without requiring explicit using statements.

Namespaces may be duplicated across assemblies.

Note that defining your type in the same namespace does not grant you access to internal members of types defined in the same namespace but different assembly.

Drew Noakes