Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nested namespaces

Tags:

c#

I've got something like this:

namespace n1 {     namespace n2     {         class foo{}     } } 

In other file I write:

using n1; 

Why I can't type now something like:

n2.foo smthing; 

And how to make something like this possibile?

like image 876
Neomex Avatar asked Jun 09 '11 18:06

Neomex


People also ask

What is a nested namespace?

A namespace inside a namespace is called a nested namespace in C#. This is mainly done to properly structure your code. We have an outer namespace − namespace outer {} Within that, we have an inner namespace inside the outer namespace − namespace inner { public class innerClass { public void display() { Console.

Can we have nested namespace in C++?

In C++, namespaces can be nested, and resolution of namespace variables is hierarchical. For example, in the following code, namespace inner is created inside namespace outer, which is inside the global namespace.

What is the use of nested namespace in C#?

When a Namespace is declared inside the other namespace that declaration is called nesting namespaces. When a Namespace is declared inside the other namespace that declaration is called nesting namespaces. You can nest namespaces to any level you want.

Can you have a namespace in a namespace?

A namespace can also be defined in multiple scopes and if a namespace is unnamed, the variables and functions specified within them can be explicitly accessed in the same manner that global variables are accessed. The namespaces in some namespaces may also be nested.


1 Answers

This is a deliberate rule of C#. If you do this:

namespace Frobozz {     namespace Magic     {         class Lamp {}     }      class Foo     {         Magic.Lamp myLamp; // Legal; Magic means Frobozz.Magic when inside Frobozz     } } 

That is legal. But this is not:

namespace Frobozz {     namespace Magic     {         class Lamp {}     } }  namespace Flathead {     using Frobozz;     class Bar     {         Magic.Lamp myLamp; // Illegal; merely using Frobozz does not bring Magic into scope     } } 

The rule of C# that describes this is in section 7.6.2 of the C# 4 spec. This is a very confusing section; the bit you want is the paragraph near the end that says

Otherwise, if the namespaces imported by the using-namespace-directives of the namespace declaration contain exactly one type having name I...

The key point is that it says "exactly one type", not "exactly one type or namespace". We deliberately disallow you "slicing" a namespace name like this when you are outside of that namespace because it is potentially confusing. As others have said, if you want to do that sort of thing, fully qualify it once in a using-alias directive and then use the alias.

like image 137
Eric Lippert Avatar answered Oct 05 '22 15:10

Eric Lippert