-3

C# code

I am a new c# learner, that' why I have some of the dumbest question! But I want to know if we have already used "using System" statement in our app then why do we need to use statements like "using System.Data" or any other shown in the image. Haven't we already imported the main namespace, then why is there even need of adding using statements for sub-namespaces?

Stephen Kennedy
  • 20,585
  • 22
  • 95
  • 108
Jai Sharma
  • 113
  • 9
  • 1
    Namespaces don't have a 'containership' relationship. They stand alone. – Dave Mar 18 '18 at 09:19
  • 1
    I'm surprised that you didn't simply try removing the other ones. You would soon see that it doesn't import everything at the System level. – ProgrammingLlama Mar 18 '18 at 09:23
  • Well, I did know that namespaces were not being imported at system level. My question was rather on the "Why" part! – Jai Sharma Mar 18 '18 at 09:25

2 Answers2

5

Because the Language Spec says so:

C# language specification section 9.4.2 Using namespace directives:

A using-namespace-directive imports the types contained in the given namespace, but specifically does not import nested namespaces.

A reason for this might be that if every nested namespace is imported, then there would be too many name conflicts. This reduces the benefits of using using directives.

Here are some name conflicts that I could think of if using directives imported nested namespaces:

  • System.Drawing.Path and System.IO.Path
  • System.Windows.Forms.Button and System.Web.UI.WebControls.Button
  • System.Timers.Timer, System.Threading.Timer and System.Windows.Forms.Timer
Aleks Andreev
  • 7,016
  • 8
  • 29
  • 37
Sweeper
  • 213,210
  • 22
  • 193
  • 313
0

Because using is not recursive down the namespace tree. When you import System you import only the definitions strictly inside System not the ones inside System.Collections. That's why you need to specify them.

ema
  • 5,668
  • 1
  • 25
  • 31