C # - Type declaration in namespace

which may be possible using type declarations in the namespace, but not in the class.

For ex:

namespace Test { public delegate void Ispossible(); } 

This is valid and does not generate compilation errors, but I cannot figure out why we declare it this way, and not inside the class.

+4
source share
4 answers

The namespace is a high-level unit of organization within .NET.

Declaring types within classes is usually underestimated (but, as in all cases, this is not a 100% rule), since it can make types more closely related and more difficult to find.

VB.NET modules are a bit of an exception (editing: they are really more of a compiler / syntax sugar trick), but usually everything in the .NET ecosystem is contained in a namespace.

Your example allows reuse; if it were in a class, it would mean that the delegate should be used only by this class and would likely result in duplicate delegates being uselessly introduced.


Update. When working with multiple instances of the namespace, the space is not very useful, but without them, a project of any size would be an organizational disaster. Imagine a .NET platform without namespaces; one (possibly outdated) account puts a structure in 3500 types.

Namespaces are like folders or drawers for documents; A few bulk papers are easy to manage, but if you have many pages, then finding the one you need becomes painful.

Give the documentation read, short and not very complicated (no namespace), but has a couple of decent MSDN points - namespace (C #)

+6
source

If it is a multi-purpose delegate, such as Func<TResult> , an EventHandler that is not associated with a particular class, then you must declare it directly in the namespace.

+4
source

Your phrase ("which may be possible using type declarations in the namespace, but not in the class."), Indicates that you distinguish between "types" and "classes". There's nothing here. A class is a type.

So, under what conditions do you want to declare a class directly in the namespace (i.e. how is this usually done)? The same reasons apply to other types of types.

+2
source

Both namespaces and classes can be used to organize information in a hierarchy. However, namespaces allow you to distribute a definition across dll boundaries, but classes do not. In addition, classes require you to put the class name in front of the type name, but namespaces allow you to use the "using" keyword.

So, if you want to define delegates in the same namespace in different dlls, you use namespaces.

If you want to force people to prefix a type name with any other name, without being able to rely on the namespace context, then you use classes.

0
source

Source: https://habr.com/ru/post/1302507/


All Articles