Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# - Declaration of types within a namespace

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.

like image 239
SoftwareGeek Avatar asked Feb 26 '10 17:02

SoftwareGeek


2 Answers

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#)

like image 182
STW Avatar answered Sep 30 '22 01:09

STW


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.

like image 26
Darin Dimitrov Avatar answered Sep 30 '22 00:09

Darin Dimitrov