How does namespaces work in C#?

Asked

Viewed 6,910 times

42

I’m studying C# and I came across namespaces.

How it works and when it’s applied?

If possible some basic example.

4 answers

42


Function

Namespaces are confused by many programmers. There are two useful understandings.

First to organize your types logically. It is as if you put certain types (classes, structures, enumerations, delegations, interfaces, etc.) that are related in some way in the same "box". The syntax of the language gives a good indication that this is what happens. But it is misleading.

The second understanding is disambiguate names of types that seem to be conflicting. That is, you can have two or more types with the same name in your application (within your project or externally), as long as they are in namespaces different.

It doesn’t encapsulate anything

This understanding shows that despite the vision that programmers have about the namespace be a module, a type box (as the first function indicates), in fact it works as a surname for the types. A surname works as a way to name a family. So you can have two Ricardoin the same environment without confusion, because one is Oliveira and the other is Silva.

So when you create:

namespace Estoque {
    public class FormCadastro { ... }
}

In fact it is created internally:

public class Estoque.FormCadastro { ... }

The namespace disappears and gives way to a surname for the type. So even though it’s a good idea to see the namespace as a box that group types, this idea gives a wrong impression of the concept.

Think about it, if it was a real box, could you have this separate box in several pieces? Or worse, could you have the same box in several places? Physically it is impossible. And the namespace allows it. So it is not a box, it is a surname. You can have the same family (same surname) separated in several places. Some members are in one place (one source file) and others are in another. In fact it is recommended to have only one member (one type) in each file).

Compound surnames

You may have more than one surname. For example when you have one namespace System.Collections. You are saying that the surname is composed of two words. You do not have a family called System and within this family a sub-family called Collections. Some people may understand that by putting a using System at its source will include all types of System.Collections and this idea is wrong. They are independent (family) things. There is no tree concept of namespaces. Since they’re not boxes, the namespaces cannot be inside each other.

Saving typing

The advantage of being considered something separate from the type name and not an integral part is that you can use these types without the last name, as long as you indicate in which family you should look for the member (by type). This is done with the directive using. More information in that reply.

The idea that the using functions as a include is not true. One may think so to facilitate understanding, but in reality the closest to include which is done in . NET is to include a Assembly in the project (create a reference for it). Manually it would include something like this:

<References>
  <Reference
    Name = "Lib1"
    AssemblyName = "Lib1"
    HintPath = "\\BuildServer\Latest\Release\SharedComponent\SomeControl.dll"
  />
</References>

Modules in the . NET

In C#, or . NET as a whole, it is possible to have the concept of real box. This is done through the Assembly. See more in this answer.

The idea of include is closer to Java packages. Although the package of Java is a conjunction of Assembly and of namespace found in C# and VB.NET. These languages separate concepts.

Completion

It is necessary to understand what logical groupings are. This is not a concept of language, but a way to organize your projects. You will probably want to organize everything that is part of the Estoque in the same namespace, all are part of the family Estoque. Some people may be tempted to group all the Formss of the application in the same namespace but this would normally be a mistake. You are putting strange members in the same family just because they "practice the same profession".

I put in the Github for future reference.

  • Good analogy with surnames.

  • @Washingtondacosta didn’t even need to be very creative, because that’s exactly what he is :)

27

Namespaces are for two things in my view:

  • organize the code by grouping classes, structures and the like

  • avoid class name conflicts, structures, delegates, etc..

What the namespace means

When you create classes and others within a namespace, namespace is actually part of that class name.

namespace EspacoNomes
{
    public class MinhaClasse
    {
    }
}

In fact the full name of this class is EspacoNomes.MinhaClasse.

Using classes without full name

The full class name can be reduced to only MinhaClasse when using the usings at the top of the file, or at the beginning of the namespace:

using EspacoNomes; // faz com que todas as classes dentro do namespace possam
                   // ser referidas somente pelo nome final da classe

It is also possible to completely rename a class with a using:

using NovoNome = EspacoNomes.MinhaClasse

Reference can now be made to EspacoNomes.MinhaClasse simply using NovoNome.

Another important thing is that when a code is inside a namespace, it can directly reference everything that is directly in the same namespace. For example, two classes within the same namespace can refer to each other using only the final class name.

  • Is there anything similar to apply to Forms? for example if I want to separate registration forms, queries and etc?

  • 1

    You can use your own namespaces for that. Just change the namespace and you’re done.

20

namespaces in are sets of identifiers that serve to group common functionalities. For example, in an MVC project, I have a namespace for models (Models), one for controllers (Controllers) and one for visions (Views).

In the declaration of a class, when we make use of another class (using the declaration using), the use of namespaces is useful because the inclusion of a namespace in using makes it possible for the class in question to have access to all the items implemented in that namespace. In the MVC example, if used using MeuProjeto.Controllers in some source, all classes marked with the namespace MeuProjeto.Controllers will be accessible at this source.

  • 4

    You’re wrong about the internals... they are visible throughout the Assembly, provided it is by other code within the same Assembly.

  • 1

    I can’t remember where I read that internal value only within the namespace, but you’re right. I edited the answer. Thank you!

1

Better saying a namespace is a middle of a class, struct, variable be localized.

guy:


namespace loc{
  public class usuario : Form { }
}

the namespace in an external location:


using loc; // a namespace utilizada acima

class Program{
   void Main(){
     usuario u =new usuario(); u.ShowDialog();
   }
}

if you want to use a class of a namespace without using it for whole use the code:


using Thread = System.Threading.Thread;

class App{
 public App()
{
  Thread.Sleep(100); // em vez de usar System.Threading.Thread.Sleep(100); / using System.Threading.Thread;
}
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.