views:

91

answers:

4

Hi folks, what could be a possible use of declaring types within a namespace but not in a class.

For ex:

namespace Test
{
    public delegate void Ispossible();
}

This is valid & does not generate any compilation errors but i can't think of why we would declare it this way as opposed to inside a class.

+3  A: 

If it is a multi purpose delegate such as Func<TResult>, EventHandler which is not related to a particular class then you should declare it in the namespace directly.

Darin Dimitrov
+5  A: 

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

Declaring types within classes is typically frowned upon (but, as with all things, it's not a 100% rule) because it can make the types more tightly coupled and more difficult to find.

VB.NET Modules are somewhat of an exception (edit: they're really more of a compiler trick/syntactical-sugar), but normally everything in the .NET ecosystem is contained in a namespace.

Your example lends itself to reuse; if it were within a class then it would imply that delegate should only be used by that class and would likely lead to duplicate delegates needlessly being introduced.


Update: When working with only a handful of types namespaces don't seem of much use, but without them a project of any size would be an organizational catastrophe. Imagine the .NET framework without namespaces, one (probably long outdated) count puts the framework at 3500 Types.

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

Give the documentation a read, it's short and not terribly complicated (neither are namespaces) but has a couple decent points MSDN - Namespace (c#)

STW
+2  A: 

Your phrasing ("what could be a possible use of declaring types within a namespace but not in a class."), indicates that you draw a distinction betweens "types" and "classes". There is none. A class is a type.

So, under what conditions would you want to declare a class directly in a namespace (i.e, the way it is most commonly done) ? These same reasons apply to other kinds of types.

James Curran
thanks but i was referring to types other than a class like events, delegates, etc.
SoftwareGeek
Re-read my last sentence.
James Curran
A: 

Both namespaces and classes can be used to organize information in hierarchy. However namespaces allow to distribute definition across dll boundaries, but classes do not. Also classes require to put class name before type name, but namespaces allow to use keyword "using".

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

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

alpav