0

When using visual studio express to create a console C# application, I found that some namespaces are automatically added at the top of code at start:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

My understanding is first directive should allow me to use things defined in System and rest three directives are for namespaces which are defined within the overall System namespace which is already referred in first directive. Then why is VS 2013 adding rest of three using directives ?

4 Answers4

2

You're misunderstanding how namespaces work.

For example, say I could define two classes, in two separate namespaces:

namespace MyNamespace
{
    public class One
    {

    }
}

namespace MyNameSpace.SubNameSpace
{
    public class Two
    {

    }
}

And then I want to create an instance of each in another class, like this:

var one = new One();
var two = new Two();

I'd have to include two using directives in order to do that.

using MyNamespace;
using MyNameSpace.SubNameSpace;

Including only the first using directive is not enough; it doesn't automatically include classes defined in the second namespace.

Grant Winney
  • 65,241
  • 13
  • 115
  • 165
  • Then why not define a new namespace with the name SubNameSpace ? What purpose does adding a '.' serves ? – Kaustubh Kaluskar May 18 '15 at 03:32
  • 1
    @kk_139 This prevents name clash when 3rd party lib/dll kicks in. e.g. Company ABC and Company XYZ may define their unique namespace prefix like `ABC.SubNamespace` and `XYZ.SubNamespace` – Neverever May 18 '15 at 03:52
1

The using system does not automatically include everything within sub-namespaces. The first namespace (System) does NOT bring in the following three.

Steven Hansen
  • 3,189
  • 2
  • 16
  • 12
1

I think that the way to look at namespaces is that the "." is just another character in the name that makes it easier for humans to understand heirarchies of related namespaces and as far as Visual Studio is concerned, those are two distinct namespaces.

John Hodge
  • 1,645
  • 1
  • 13
  • 13
  • As far as .NET is concerned, yes, but C# allows you to create namespace names with dots in the middle using nested namespace statements. – Tom Blodget May 18 '15 at 04:08
0

You can treat the like this

namespace System {

//... stuff
     namespace Linq {
     }
...

}

Namespace of System is different from namespace of System.linq. The first line will allow you to use System.Console. But the first line alone won't allow you to use methods in namespace System.Linq.

CS Pei
  • 10,869
  • 1
  • 27
  • 46