Why I can access class that is defined outside of namespace?

I was wondering Why I can access class when I defined it outside of namespace scope?

I am not very familiar with namespaces, I am just learning, but I thought that namespace should like wrap all my classes to one 'box' and they can access each other just inside that 'box' (scope).

Code example:

class Point
{
    public int X;
}

namespace ConsoleApplication12
{
    class Program
    {
        static void Main(string[] args)
        {
            Point p = new Point();
            p.X = 50;
            Console.WriteLine(p.X);
            Console.ReadLine();
        }
    }
}

Thank you for answers.

Jon Skeet
people
quotationmark

Namespaces have nothing to do with access. It's important to differentiate between namespaces and assemblies - they're often closely related, in that types in a namespace Foo.Bar would be likely to be in assembly Foo.Bar.dll, but that's a convention - it's not something the compiler or language cares about.

A namespace is primarily "a space in which names have to be unique". In other words, while it's fine to have two types called Point in different namespaces, you can't have two types called Point in the same namespace. Indeed, the primary reason for namespaces existing (IMO) is so that we don't all have to use completely unique names across every piece of .NET code in the world.

You can use your Point class which is implicitly internal so long as it's declared within the same assembly. If it's in the global namespace (i.e. not declared in a namespace at all) then you don't need any using directives to refer to it - the purpose of a using directive is to allow you to refer to members of a different namespace just by their short name.

So if you have:

namespace Foo.Bar
{
    public class Baz {}
}

then you could access that as either:

namespace Other
{
    class Test
    {
        Foo.Bar.Baz baz = new Foo.Bar.Baz();
    }
}

or

// Allow anything in namespace Foo.Bar to be accessed by its
// short name
using Foo.Bar;

namespace Other
{
    class Test
    {
        Baz baz = new Baz();
    }
}

If the type is defined in the "global" namespace, then you just don't need the using directive. From the C# 5 language specification section 3.8 (namespace and type names) where it's describing the type name lookup procedure:

If the previous steps were unsuccessful then, for each namespace N, starting with the namespace in which the namespace-or-type-name occurs, continuing with each enclosing namespace (if any), and ending with the global namespace, the following steps are evaluated until an entity is located

So in your case, looking for Point from your Main method, first ConsoleApplication12 would be checked for a Point type, then the global namespace.

people

See more on this question at Stackoverflow