basic question on C# - do I need a namespace? - c#

I am a Java developer, totally new to C#. I am currently writing a DLL for distribution across my organization. It is a very simple library containing a couple of classes and I do not see any real use in putting all of them into some namespace just for the sake of it. Do I really have to use a namespace? If so, why? Is it some kind of a best practice?

Do you need one? No. Should you have one? Yes. It'll help prevent clashes with identically named classes in other namespaces without having to resort to the (IMHO) ugly use of global::.

For throwaway test apps (e.g. checking Stack Overflow answers), I don't use a namespace. For anything else, I do. It's just an organization thing - if you're going to reuse code, it's helpful to separate it from other code you're also reusing in the same context. What I mean is, if you're creating an app using LibraryX and LibraryY, it's useful to be able to differentiate between them within the app. It's possible that they both use the same class names, for example - which will make the code ugly if you don't use namespaces.
Aside from anything else, if you're coding with Visual Studio it's actually more work not to include a namespace - you've got to modify the project to give it an empty default namespace.

There is no need to have a namespace. However developer studio expects you to be using a name space. For example, when you choose to add a class to a project developer studio will:
Create a file for the class
Add the file to the project
Create an empty class (in the above file) that is in the project’s default namespace.
A “project’s default namespace” is a developer studio concept not a C# concept and is set in the properties of the project.
As you are creating a dll for others to use, it will be a lot easier for the users of your dll if you have a name space:
People expect you to have a namespace (so may be confused if you don’t)
Namespaces make it a lot easier for your users if you have class (or enum etc) that is named the same as another class in any dll they are linking to.
Therefore I don’t see a good reason not to use a namespace.

My vote for "yes" i think it is good habit to use namespace. you can not be sure that people won't use same class names.

To respond to your comment about naming a class the same as it's namespace, read a little bit of the following article.
Short version: don't do that.
http://blogs.msdn.com/b/ericlippert/archive/2010/03/09/do-not-name-a-class-the-same-as-its-namespace-part-one.aspx

Basically System is a root namespace in asp.net C#.
In .net every programs is create with a default name space. This default namespace is called global name space. But program itself create any numbers of namespace, each of unique name.
learn more
http://asp-net-by-parijat.blogspot.in/2015/08/what-is-namespace-in-c-need-of.html

Related

Pitfalls of creating extensions to the .net System libraries inside the System namespace

At all the companies I have worked at I end up championing a core set of libraries that do nothing more than enhance and extend the .net libraries. Usually I have the namespaces such that they start with our company name but the sub namespaces mirror those of the System namespace.
Foo.IO;
Foo.Web
What I plan to do is take this one step further and replace the company namespace with the system namespace so that you only have to have the one using statement and thus have a better enhancement to the core library.
namespace System.IO
{
public static class StreamExtensions
{
...
}
}
The actual question
Now I know that this is possible, Microsoft do it in their own libraries and I have seen it done in other third party libraries but what I want to know is what, if any, are the long term implications of doing this such as a class name conflict in later versions of .net? Has anyone done this and had to handle a complication that has broken the simplicity of just being able to add an assembly reference?
UPDATE
Unfortunately this has turned into more of a debate of whether you should or should not do this which probably belongs over on Programmers. Indecently there is another SO question which does ask this but that was not the point of the question.
I wanted to know if there is a scenario that would crop up further down the road that would cause compilation errors or a strange behavior. The only two arguments that have come up is.
Microsoft adds a method to an object that matches the signature of extension method in the library but this is a mute point as it would make no difference to what namespace the extension method lives in as the implementation on the object would take precedence.
Someone else does the same thing in their third party library and we have a name clash. This is more likely and something we already have to deal with where third party libraries ILMerge other libraries into their assembly.
Just to be clear this is a stand alone library, it is for in house use, not to be made available externally and is there to extend the existing System libraries through Extension methods.
I would suggest do not do this. System namespace is .NET Framework namespace, if you want to customize classes from that namespace, make it explicit in your code.
That means make the customized class part of you custom namespace.
Do not mess up the things.
This may be a little off-topic, but in reference to the alternative approach you mention:
Usually I have the namespaces such that they start with our company name but the sub namespaces mirror those of the System namespace.
I've had some issues with that approach.
My company name is Resolv - as such, a lot of the stuff I write ends up going into a namespace in the form of Resolv.<ProjectName> (the rest will be <ClientName>.<ProjectName>).
I started building my library of extension methods, static classes and so-on in a namespace called Resolv.System
However, that created namespace resolution issues when using "fully qualified" type names that start with System (e.g. var myVar = new System.Collections.List<int>();).
While I would never use a fully qualified name in that particular case, it's something I do on occasion if the type I'm referencing is the only one from that namespace in the entire code file (in which case adding a using isn't warranted) - or on those occasions when two namespaces imported (with using statements) contain conflicting type names. Automated code generation tools (like resharper) often add those sort of references when there isn't an appropriate using statement too.
If I'm working on code within some namespace anywhere inside Resolv (e.g. Resolv.MyInternalProject) - and I put in what should be a fully qualified name - confusion ensues because of the Resolv.System namespace. The compiler walks back up the current namespace, gets to Resolv and then finds Resolv.System. That means - for example - that new System.Collections.List<int>() will attempt to use the non-existent class Resolv.System.Collections.List<int>().
Of course, I can get around that by using the form var myVar = new global::System.Collections.List<int>() but that's ugly and sort of a pain).
I've opted instead to include a "project name" in my extensions namespace tree, so now instead of Resolv.System I have Resolv.Extensions.System. From there the child namespaces mirror the System namespace (e.g. Resolv.Extensions.System.IO). That way I can have better control over whether I want to have System.xxx.xxxx references refer to my extensions, or the .net ones from any given code file (and it's only one using statement to add to my code files when I want to "turn on extensions").
Of course, I'll still have the System.xxx.xxx namespace confusion when working on code inside the Resolv.Extensions namespace - but that won't bug me on a daily basis! :)
What I plan to do is take this one step further and replace the
company namespace with the system namespace so that you only have to
have the one using statement and thus have a better enhancement to the
core library.
I don't understand how this will enchance the core library. What happens when Microsoft adds the same method to the String class and it does something entirely different? This is the reason they should be in their own namespace.
Now I know that this is possible, Microsoft do it in their own
libraries and I have seen it done in other third party libraries but
what I want to know is what, if any, are the long term implications of
doing this such as a class name conflict in later versions of .net?
The long term implications is if Microsoft adds the same method to a class as the extension method you create.
Has anyone done this and had to handle a complication that has broken
the simplicity of just being able to add an assembly reference?
I don't understand the reason you want to reduce the amount of references. You gain nothing by doing this, having utility methods in their own namespace and class is a valid design decision, people assume they will be seperate and not part of a Microsoft namespace.
It is a valid statement but the question about what are the
implications. Other people, including myself, have shied away from
doing this because of a "gut" feeling about messing with someone
else's namespace but no one has said do not do it because of this. If
you have a specific factual reason I would love to hear it.
The implication is a developers assumptions that the System namespace is filled with only Microsoft code.

C#: Un-nested struct in same .cs file as related class?

If I'm dealing with one class and one public struct (not nested), Should I create a separate .cs just for the struct? Or leave it un-nested in its .cs file of the class? (This is assuming the struct relates to the class, but isn't so exclusive to the class that it should be nested and declared private)
Edit: I removed my initial question about two classes because I found C# classes in separate files?
Note that the only person(s) that can accurately answer this question is you, and your team. If your team is happy to find several related types inside a single file, combined due to ... whatever... then what I, or whomever other person, says, should be just ... irrelevant.
In any case, I would turn the question upside down:
Is there any reason to place two separate types (related by names, functionality, or whatever, but separate nonetheless) in the same file
and I've yet to come up with a good reason.
There are extensions/addins to Visual Studio where you can type in the name, and quickly navigate to the file, and I can think of three, but there are undoubtedly others:
DPack
ReSharper
CodeRush/Refactor! Pro
The first allows you to quickly navigate to a file by name. If you know the type, but have people putting multiple types into the same type, this will not be helpful, at all.
The second and third, lets you navigate to a type by name, but you shouldn't rely on people having those, or knowing how to use them.
To that end, I would advocate following these rules:
Project names should be identical to the root namespace of that project. I differ from this point myself where in some cases I name my projects "...Core", and I then remove "Core" from the namespace, but otherwise, leave the project name identical to the namespace
Use folders in the project to build namespace hierarchies
The name of a type should correspond 100% to the name of the file + whatever extension is right for your language. So "YourType" should be "YourType.cs", "YourType.vb" or "YourType.whatever" depending on language
That depends on who you ask.
I, personally, find it easier to read if they are all, always, broken out. However, the compiler doesn't care... so whatever you and your team agree is easier to understand.
In my opinion it's a good practice to avoid that. Some day a developer will be looking around for ClassBar in the project and won't be able to find it easily because it's nested in ClassFoo.cs
Tools like Resharper have a neat feature where you can just select a class, right click, place in new file to make this easier.
If you read any of the popular coding standards (Lance Hunt, iDesign, Framework Design Guidelines etc) most of them advocate 1 class per file.
Its annoying to scroll down and search for how many class each.cs file contains/hides.
Maintainability issue while using version control
Usability with our team.
Check here for more interesting discussion on same.
I think it was less about whether you can or whether you should. For things like this, I feel it's best to look to the convention in the rest of the codebase. Sometime conformity is better because it makes other developers jobs easier becaues everybody knows where things are.
If it's entirely new project and you are setting the standards here by yourself, do what makes sense to you. To me if the struct has no use outside the related class, I may put them in the same file. Otherwise, I seperate them out.

Is this the good pratice to name the namespace according to the directory name

I have a directory structure to store the source files. Is this the good practice to
name the naming space according to the directory structure?
Like
Models\model.cs
Data\data.cs
One is defined in namespace Models
One is defined in namespace Data
Yes, that's the typical approach, and it's also one that's supported by tools such as ReSharper.
The difference between this and the Java approach is that you don't add directories all the way down from the top - just from the default namespace for the project. So for example, suppose we were creating Foo.Bar.Baz.Model and Foo.Bar.Baz.Data, the C# and java solutions might be:
C#:
Foo.Bar.Baz
Foo.Bar.Baz.csproj defining a project with default namespace of Foo.Bar.Baz
Model\
SomeModel.cs
Data\
SomeData.cs
Java:
src\
foo\
bar\
baz\
model\
SomeModel.java
data\
SomeData.java
yes is the usual practice, but you also put the project name before the directory name so you will have: myclasslibraryname.Models.Model and myclasslibraryname.Data.Data
Yes. It is a common practice in Java (at least, the source code I've looked at for big projects has almost always been structured this way). Not as common in C# from what I've seen, but there's nothing keeping you from doing it, and it helps you find the code a lot faster.
You'll probably want a deeper namespace hierarchy than just one level though. It is common to preface it with your organization or group name, the project name, the library/program name, then code architectural names (like Model, View, Data, etc). Whatever makes the most sense for whatever scope the source code of your project will live.
Generally I think it is a good practice. When you do it in such a manner, while going through the code, you can generally associate or easy to locate and get to know where your code file is coming from.
This is also a good practice in terms for maintaining the code. Some new user comes in, he can just see the namespace and identify where the code files are located or needs to be searched.
I don't know really if this is good or not.
But I name it like this.
I defined categories for the different modules.
Like this:
Company.Common
Company.Common.Web
Company.Windows
Company.Windows.Services
Common represent a directory. Inside it I created a solution with VS2010.
Inside the solution I create a project for each part and therefor the subdirectories for the project and if the project is complex, more sub dirs for the existing classes inside the dll.
There I have a good overview in all views (dir - view and project view - code view ).
This is a convenient convention for many projects, and one which some tools support or expect.
However, this isn't the full story. Although it's a good default, I don't think it should be regarded as inviolable best practice, because there are some circumstances which might motivate doing things another way. Additional factors to think about include:
Unnecessary namespace proliferation
and deeply nested namespace
hierarchies can be a pain for users
of your types. In a large library you
may want to start organising the
source code files into some folder
structure before you feel the need to
impose multiple namespaces on your
clients.
Related to this, namespace
hierarchies in .NET are supposed to
work such that dependencies between
types go from child namespace to
parent, not the other way around.
This isn't always the natural way to
organise source code into
folders/directories. For example, one
often sees people creating namespaces
such as MyNamespace.Foo.Common
containing utility types used both by
types in MyNamespace.Foo.Bar1 and
those in MyNamespace.Foo.Bar2. It
seems sensible to them at the source
code organisation level, but it
breaks the namespace dependency
convention.
Sometimes you may want to provide
additional functionality by adding
some types to a library namespace by
distributing a supplementary assembly
rather than releasing a completely
new version of the full library
assembly. It's likely to be more
convenient to keep source code files
for the respective assemblies
separate from each other in the
repository, rather than to store them
together just so as to keep all types
for the namespace in the same folder.
In short, I'd say follow the usual practice unless you have a good reason to do otherwise. But don't let it deter you, if you have a good reason to make use of the fact that Namespaces can provide a grouping of types completely orthogonal to their grouping into deployable assemblies and the source code which builds those.

Class library reference problem

I am building a class library and using its default namespace as "System". There suppose I am creating a generic data structure say PriorityQueue and putting it under System.Collections.Generic namespace.
Now when I am referencing that library from another project, I can't see PriorityQueue under "System.Collections.Generic" namespace anymore. Though the library is referenced I can not access any of the classes in it.
Can anyone shed some light on it please. I know that if I change the namespace everything will be ok, but I want to create a seamless integration like .net framework itself with other project, so that one can refer the library and forget about its namespaces.
This is a very bad idea. Pretend you didn't think it up, and use a real namespace.
One does not have "seamless integration" with the .NET Framework, either. If we want to access the List<T> class, then we have to write
using System.Collections.Generic;
If you put your class in MyCompany.Collections.Generic, then you'll get exactly the same level of "seamlessness" that is achieved by the .NET Framework itself.
If you are using the System namespace for your classes, then they will be found in System.
If you want them to be found in System.Collections.Generic, then you need to place them there.
But let's be clear, placing classes in System.* is a bad idea.
Putting stuff in system namespaces is a bad idea. Firstly it's better to know explicitly where the stuff your using is. However more importantly, if Microsoft releases new stuff that causes a naming conflict with yours, your stuff breaks.
The second reason is probably why you cant see your code.
Just create your own namespace, e.g. Anindya.Collections.Generic, as placing classes in predefined framework namespaces isn't a good idea. MS might introduce a same class in a later framework, leading to problems.
Did somebody mention yet that this is a bad idea? There are few reasons you wouldn't be able to see the class. Short from the assembly reference, there is only one good one: you forgot to declare the class public.
In case it wasn't clear: This is a REALLY bad idea.
The System name space should be considered reserved and verboten. If Microsoft decides to introduce a class in a framework update that conflicts with your System.mycrap.blah identifier in the future, you're going to have some pretty hefty refactoring on your hands, and, in the case of an app that's deployed to a client, an emergency update and potential liability for system downtime.
You wouldn't create your own class called "String." By the same token (pun), don't use reserved namespaces.
Also, the namespace "System" doesn't really describe the contents of your namespace. Typically, namespaces should mean something - like, BlogEngine, DatabaseCore, etc. Slapping everything into System is a lot like naming all of your variables "x," or "temp," and implies that the creator doesn't really understand the point of this level of code delineation and organization.

Best practices: C# Extension methods namespace and promoting extension methods

I know there exists already a post, describing nearly the same, but I think mine is a bit different.
What I would like to know is how you organize your extension methods in terms of assigning the namespace. Currently - for the extension methods in our framework - I use the following namespace pattern
MyCompany.Web.Utils
and inside I have the extension method classes. This is fine for me with the disadvantage that the extenders are not immediately visible to our software developers. Consider the case where I have a StringExtender class which provides a quite handy extension method "In" that extends the String object. Having the extension method withing the above mentioned namespace, our programmers won't see the extension method unless they explicitly include its namespace. Instead, if I would put the extension method in the System namespace, everyone would immediately see it, but I've read that this is bad practice.
So my question is how you do promote your extension methods s.t. they are used by your developers.
We put them all in their own namespace Company.Common.Extensions. That way, if you have any of our extension methods, you have them all. Plus, at least at my shop, we don't have to worry about our developers not knowing about extension methods. I have the opposite worry, extension method overload! :)
The problem here is not the naming of the namespace, it's the lack of documentation and education of your developers.
Put them in whatever namespace makes sense, write a wiki article documenting all your extension methods, then send an email to your developers with a link to the wiki article.
This is not a namespace problem it is a communication problem.
If these methods are useful you need to communicate this to the developers and, conversely, act on the feedback from them (with appropriate levels of judgement).
Placing anything into the System namespace is a recipe for disaster and confusion later. The only times you ever want to do this is to 'back port' functionality into older frameworks and then you probably shouldn't do it yourself but should use something like LinqBridge to do it.
Be wary of the desire to throw all extensions into one namespace unless they really are widely useful together. Some developers may find the wood lost for the trees if they are bombarded with everything and the kitchen sink via intellisense.
Keeping the namespace the company name is sensible in general to avoid confusion.
#Juri- If you think about it this is the same problem as developers knowing that class X exists in the .NET framework. Communication is key that all team members use the right classes, be they extension methods or some other helper.
As JP has stated, I often see extension methods in some kind of subfolder called Extensions. Hopefully when you state you use my.company.web.utils the namespace is actually Pascal cased?
Even if you put them in a good place there is no 100% guarantee that other developers will use them.
Presuming you use Visual Studio, one way would be to create a custom Class template (or modify the default one) so that whenever a developer creates a new class file it automatically has a using statement with your namespace(s). See Customize Visual Studio 2005 Templates for Coding Productivity.
Yes,i think put the Extension methods in own company namespce is best practices. put it in System namespace is a lazy operation
I'm dumb, lazy and minimalistic, so I put them at the same namespace as the type they extend. In this way there is no need for extra using statements, documentation or emailing about them (Winston).
I like the way ReSharper solves this problem.
ReSharper discovers any available extension methods, even without the corresponding usings. In case the using is not present, Intellisense also shows the namespace where the extension resides, making clear where the extension comes from and indicating that selecting it will add the using. (Example below.)
Naturally, only namespaces reachable by the current project, i.e. directly or indirectly referenced, are included.
Here is an example of what Intellisense might show if there are two extension methods. The first one comes from a namespace that we have already included. The second comes from a namespace that we have not (yet) included.
AddMvc
AddEntityFrameworkSqlServer (Microsoft.Extensions.DependencyInjection)
We put everything into the same Namespace and Class, however we use partial classes to keep them organized.
For example:
ExtensionMethods-String.cs
ExtensionMethods-DataObject.cs
ExtensionMethods-Debug.cs
...etc all have partial classes...
You can achieve what you want by putting extension methods in the global namespace. That's what I do and they're then available without needing any using statements.

Categories