Use of Namespaces in C# - c#

I was wondering, what the purpose of Namespaces in C# and other programming languages is...
As far as I know, they are used for two things:
To structure the project into meaningful pieces
To distinguish classes with the same name
My Question is: Are there any other things to consider when using namespaces? Do they have an impact on performance or something like that?

As far as I know, they are used for two things:
• To structure the project into meaningful pieces
• To distinguish classes with the same name
That's basically it. I would add to your first point that namespaces provide structure larger than just that of the project, since namespaces may span projects and assemblies. I would add to your second point that the primary purpose of namespaces is to add structure to libraries so that it becomes easier to find stuff you need and avoid stuff you do not need. That is, namespaces are there as a convenience for the user of a library, not for the convenience of its creators.
A secondary purpose is to disambiguate name collisions. Name collisions are in practice quite rare. (If the primary purpose of namespaces was to disambiguate collisions then one imagines there would be a lot fewer namespaces in the base class libraries!)
Are there any other things to consider when using namespaces?
Yes. There are numerous aspects to correct usage of namespaces. For example:
violating standard naming conventions can cause confusion. In particular, do not name a class the same as its namespace! (See link below for details.)
using a namespace can bring extension methods into play that you didn't expect; be careful
where precisely the "using" directive goes can subtly change resolution rules in a world where there are name collisions; these situations are rare, but confusing when they arise
collisions often arise in contexts where machine-generated code is interacting with human-generated code; be careful in such situations, particularly if you are the one writing the code generator. Be very defensive; you don't know what crazy name collisions the person writing the human-generated half is going to create.
See my articles on this subject for more details:
http://blogs.msdn.com/b/ericlippert/archive/tags/namespaces/
And see also the Framework Design Guidelines for more thoughts on correct and incorrect conventions for namespace usage.
Do they have an impact on performance or something like that?
Almost never. Namespaces are a fiction of the C# language; the underlying type system does not have "namespaces". When you say
using System;
...
class MyException : Exception
...
there is no class named "Exception". The class name is "System.Exception" -- the name has a period in it. The CLR, reflection, and the C# language all conspire to make you believe that the class is named "Exception" and it is in the namespace "System", but really there is no such beast as a namespace once you get behind the scenes. It's just a convention that you can sometimes omit the "System." from the name "System.Exception".

According to MSDN a namespace has the following properties:
They organize large code projects.
They are delimited with the . operator.
The using directive means you do not need to specify the name of the namespace for every class.
The global namespace is the »root« namespace: global::System will always refer to the .NET Framework namespace System.
Secondly namespace has nothing to do with performance but if you have created your own namespace so you should follow the conventions across the project.

It doesn't affect performance. But for code readability, I would recommended remove unwanted using statements

Namespaces are a concept pulled from earlier technology, like XML. THe namespace gives context to your classes, allowing you to have say a CUstomer object in your domain and in your data code.
You can also use namespaces to alias, which still does the above, but allows shorter naming for the particular object.
domain.customer
versus
data.customer

You've touched upon the two main reasons. This is an old article from MSDN but it still applies: Namespace Naming Guidelines
In the Java world the naming practice is to reverse the domain name of the company who owns the product and include the product's name after that. So com.example.product might be a valid namespace, but you don't really see that in .NET so much.

Those are the big ones right there.
There aren't really performance benefits. At least, not directly. without namespaces framework would have to search the a lot more places to find the code you are trying to include - It would almost be like needing to load up the ENTIRE .NET framework for every project. Well, not really, but its close enough for this discussion.

Related

Why should a type not depend on types from its containing namespace?

Also posted here, but with no real academic answer:
why namespace types should not depend on nested namespaces types?
If I understand it correctly, the point is that a type Product.Business.Modules.Module can depend on Product.Business.Product, but not the other way around, because Product is the foundation for Module. However, looking at my project structure, I violate this guideline:
namespace Product.Business
{
using Modules;
class Product
{
public IEnumerable<Module> Modules { get; }
// Module is abstract, with many different kinds defined in Modules.
}
}
However, I would like to extend the question.
Where can I find supporting information to back this guideline?
Why is this bad practice?
Is it valid to have types depend on types from other namespaces with the same containing namespace? (e.g. Product.Business.Security depending on types in Product.Business.Modules?
In a sense violating this guideline creates a sort of circular namespace dependency, but I'd like to understand more of the why of this guideline rather than just a blanket statement. The only other information I was able to find was from the linked Msdn article. This can actually change the architecture and layout of a class library significantly.
To start with, I'll address your 3rd question. I have not seen any advice against that and seems to be a reasonable thing to do. You separate namespaces logically and one branch of your code might make use of another.
When it comes to nesting the namespaces however, you are creating a hierarchy. As a hypothetical example, consider a company that is testing out some data tools they are developing: Company.Data will have abstract classes and base classes that Company.Data.SqlServer will depend on. SqlServer provides specific implementation for the abstract stuff in the containing namespace. Due to feedback or the need to support another database system, the time may come when for maintainability, they decide to move the SqlServer classes out to a different library.
It is trivial to make the new assembly reference the original Company.Data and go on. The classes in Company.Data will proceed as though nothing changed. If, however, they had dependencies on the contained namespace and/or its classes, doing so breaks Company.Data. It will defeat the purpose of separating concerns. That would mean if they make a product to support MySQL, Company.Data.MySql would have a dependency on Company.Data.SqlServer.
Techniques such as the Provider Model design Pattern will no longer be possible or viable.

Namespace writing standard and performance issue

I was under review of team code. I observe they had used class ClassAby writing using AAA.BBB; at the upper portion of the class; also they have sometime used class ClassB by AAA.BBB.ClassB. There are two basic questions.
Is there any performance issue while using above scenario. What is recommended
When I declare namespace; are all classes get loaded of that namespace or not.
Please assist here. Thanks.
I'll answer these as best as I can, I don't have any sources on hand, just experience (maybe someone can help with that).
There is no performance issue with importing a namespace versus calling it directly. When the compiler runs through it, you can think of it as always being fully qualified in the end. The using statement for namespaces is more to assist the developer so they don't have to fully qualify it each time. In fact, for your ClassB example, it could be that there is a collision with multiple namespaces defining the same class name. For example, the Calendar class is both in System.Globalization and System.Web.UI, so you have to fully qualify one or the other when using them.
Generally, all code is compiled into an assembly by the project it's under. Referencing any code inside of the assembly will load all of the associated code. Note, however that the code isn't necessarily compiled for use by the JIT until it's actually called.
Namespaces are for organizing your code (while preventing name collisions). They have no bearing on performance at all.
Fully qualified names in code are distracting and noisy. I prefer to never have them. If there is a namespace conflict, a using alias can resolve that.
only for places where there is a conflict with there being two Class defined in different namespaces, and, even then, I'll still rather use a using to differentiate them:
using MyClassB=AAA.BBB.ClassB;
// :
var myClassB= new MyNS();
in terms of performance, you can see the answer here:
The using directive is only syntactic sugar that disappears during
compilation. Whether or not the namespace was included via using or
mentioned in a fully-qualified type name is totally irrelevant in the
resulting bytecode. Hence, there is no performance benefit at runtime
by using one or the other.

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

What is best thing to call your namespace in .Net

In the past I've always gone and called my namespace for a particular project the same as the project (and principle class) e.g.:
namespace KeepAlive
{
public partial class KeepAlive : ServiceBase
{...
Then from other projects whenever i've called that class its always been:
KeepAlive.KeepAlive()...
I'm now beginning to think that this might not be such a good idea, but I'm sort of stumped what to actually call my namespace. What do other people do? Do you just have one namespace for all your projects?
We have this simple scheme:
CompanyName.ProductName
Then the application layer, e.g.
CompanyName.ProductName.Data
CompanyName.ProductName.Web
etc.
And inside divided per module and/or functionality, which normally correspond to folders
CompanyName.ProductName.Web.Shop
CompanyName.ProductName.Web.Newsletter
etc.
BTW: You can find answers to similar questions here:
.NET namespaces
Should the folders in a solution match the namespace?
Having the name of a class being the same as the namespace is a bad idea - it makes it quite tricky to refer to the right thing in some cases, in my opinion.
I usually call the project (and namespace) an appropriate name and then have "EntryPoint" or "Program" for the entry point where appropriate. In your example, I'd probably call the class "KeepAliveService".
CompanyName.ProductName.AreaOfSystem.SubAreaOfSystem
Never call them the same name as a class.
Our areas include things like:
Services
Smartcard
UI
Sub-areas are used sparingly but when relevant:
Smartcard.Mifare
Smartcard.DESFire
Ours don't correspond to folders because logically that may not be the case. To ease solution explorer navigation we might section off certain bits in folders but that doesn't necessarily mean the namespaces should follow the folder structure. Especially if there are only a few files in the folder (a namespace with few types is usually silly).
i name my namespaces with the common descriptor of all the things that go into that namespace.
I like the java package way: com.stackoverflow.Data (or whatwever the primary domain name of your company may be).
That way your namespaces won't be ambiguous.
we stick to the old
uk.co.company.system.layer
scheme that way we keep collisions down to a miniumum as we use a lot of MS Server products and it helps conceptual seperations.
eg.
uk.co.acme.biztalk.bizutils.

Namespaces in C#

I am using an ASP.NET MVC project and everytime I add a class to a folder it makes really long namespaces.
Example:
Project = Tully.Saps.Data
Folder = DataAccess/Interfaces
Namespace = Tully.Saps.Data.DataAccess.Interfaces
Folder = DataAccess/MbNetRepositories
Namespace = Tully.Saps.Data.DataAccess.MbNetRepositories
Question:
Is it best to leave the namespace alone and add the using clause to the classes that access it or change the namespace to Tully.Saps.Data for everything in this project?
Leave them alone and add the usings. You're asking for trouble manually changing things like that (harder to debug, inconsistent with other projects, et cetera).
It is really up to you how you want to deal with it. If you are only going to be accessing a member of a namespace once or twice, then adding the "using" statement really doesn't do much for you.
If you are going to use it multiple times then reducing the namespace chain is probably going to make things easier to read.
You could always change the namespace so it doesn't add the new folder name if you are just looking to logically group files together, without creating a new namespace.
According to FXCop, and I agree:
Avoid namespaces with few types
A namespace should generally have more than five types.
also (and this applies to the "single namespace" suggestion -- which is almost the same to say as no namespace)
Declare types in namespaces
A type should be defined inside a namespace to avoid duplication.
Namespaces
.Namespaces help us to define the "scope" of a set of entities in our object model or our application. This makes them a software design decision not a folder structure decision. For example, in an MVC application it would make good sense to have Model/View/Controller folders and related namespaces. So, while it is possible, in some cases, that the folder structure will match the namespace pattern we decide to use in our development, it is not required and may not be what we desire. Each namespace should be a case-by-case decision
using statements
To define using statements for a namespace is a seperate decision based on how often the object in that namespace will be referred to in code and should not in any way affect our namespace creation practice.
Leave it. It's one great example of how your IDE is dictating your coding style.
Just because the tool (Visual Studio) you are using has decided that each folder needs a new Namespace doesn't mean you do.
I personally tend to leave my "Data" projects as a single Namespace. If I have a subfolder called "Model" I don't want those files in the Something.Data.Model Namespace, I want them in Something.Data.

Categories

Resources