2

I read in http://www.dotnetperls.com/namespace the following:

Namespaces are not essential for C# programs. They are usually used to make code clearer.

This confused me alot since I had the impession that you should always use a namespace. I tried to make a win form application from VS2010 removing the namespace auto generated but the code doesn't compile.

So, my confusion comes to the question:

  • When (if) namespaces are essential in a C# Program?
ydaetskcoR
  • 53,225
  • 8
  • 158
  • 177
apomene
  • 14,282
  • 9
  • 46
  • 72

3 Answers3

7

You can write C# programs without namespaces, but you cannot access the .NET framework without them. So you actually do really need them.

david.pfx
  • 10,520
  • 3
  • 30
  • 63
3

I tried to make a win form application

The standard mistake to make here is that you removed the namespace from the YourForm.cs source code file but you forgot to do the same thing for the YourForm.Designer.cs file. Editing the Designer.cs file like that is okay. But of course adds more FUD to what you are trying to do.

There just isn't a wholeheckofalot of point to fighting the machine. Microsoft likes you to use namespaces for a good reason, they are good to avoid identifier name collisions and find a workaround when they happen anyway. You can spell the name in full. You have no such workaround available if your identifiers are all in the global namespace.

Hans Passant
  • 922,412
  • 146
  • 1,693
  • 2,536
1

I should recommend you to read this article from microsoft

you can see the following:

Whether or not you explicitly declare a namespace in a C# source file, the compiler adds a default namespace.

My recomendation to you is that you use it when you need to organize your code, example: you have 2 different types of model and you don't want them to share code

C-JARP
  • 1,028
  • 14
  • 16
  • 1
    Did you mean "you don't want theM to share the code"? I'm a self-taught semi-senior programmer who is seriously trying to guess the relevance of namespaces to keep code clean, and if I should start making namespaces myself... ultimately I'm all obsessed about Design Patterns and Refactoring Techniques... – SebasSBM Apr 23 '20 at 01:28
  • precisely, my bad, didn't see the typo there. Ultimately you can look to Namespaces as an organizational tool, where you know that a certain model for could be under the namespace NameOfTheProgram.Models, or you can even go further and have it in NameOfTheProgram.Models.NameOfTheBusinessLogic – C-JARP Oct 12 '20 at 11:04
  • In that sense, it works more or less like Python's modules when importing (more or less), doesn't it? But declaring the namespaces and stuff probably needs a concrete methodology... anyway, I will keep your words in mind... so, the next time I use namespaces with C#, I have to see them like "modules" to keep everything organized. – SebasSBM Oct 12 '20 at 18:56