Every time I creat a class, I see using System.Text that is added (amongst other using) by default. Every time I remove it after a while because it is unused according to ReSharper.
Am I missing a best practice? Do you use that namespace often? In which situation?
There has to be a reason why this namespace is referenced by default.
Thanks!
The System.Text namespace contains classes, abstract base classes and helper classes.
Say for example if you wanted to take advantage of the StringBuilder, Decoder, Encoder, etc....
The classes above, plays a significant role in most cases in .net. But it is not necessary for it to be there in your code. It only applies as to when you needed it. The important thing is to know when you will need the namespace.
It is added in visual studio by default for the convenience of the developers. Same with the
System.Linq namespace, not all of the time you will be using it but for your convenience it is already added assuming that you would be using it and that would be up to you to remove it which is by case to case basis.
Sometimes it would be a lot easier to delete it if it is not needed than to figure out the namespace and type when you need it :)
More info regarding System.Text
If it's not being used, it shouldn't be in the code. If Visual Studio adds them by default, chalk that up to Microsoft just trying to make things easy for a developer, as it thinks those are very common namespaces, but depending on what you are doing they likely aren't needed in many classes, just as you experience.
If you don't like it you can always create your own item templates. See http://msdn.microsoft.com/en-us/library/tsyyf0yh(v=VS.80).aspx
You should add using only for those namespaces that you really reference in the code.
This way the source file will not have a huge 'using header' and fewer namespace conflicts.
As you are using Resharper it is very easy to follow this rule.
If you are not using it, don't include the namespace. It is just automatically included because it is one of the more commonly used namespaces. I generally use it if I want to use regular expressions or string manipulation methods. But if you remove it and there are no compiler errors, it is safe to leave it out.
Related
At work, they've been quite elaborate with their naming of namespaces (before my time). A typical namespace could be
CompanyName.SubCompanyName.DepartmentName.ProjectName.UniqueProjectName.ProjectName.FilteredProjectName
Sadly, I'm not joking. The issue is, despite being some clarity as to where the projects live it's just so noisy; I want to shorten it.
I want to use using keyword (in regards to declaring which namespaces are to be used) and then equals symbol to use a namespace alias. The issue now turns into ambiguity between a namespace declaration and a class's property. For example
Project.Message
As it stands, we have no indication if Project is the name of a static class, a namespace or the name of an already initialised object (although the word this. would help clarify it).
So, with that background, my question is about naming conventions. For me, it would make sense to use the Hungarian style naming conventions (which I know is now considered fairly outdated these days) so I could do something like
using nsProject = CompanyName.SubCompanyName.DepartmentName.ProjectName.UniqueProjectName.ProjectName.FilteredProjectName
Please note, I've prefixed it with ns (namespace). Therefore, if the code looks like either of the following, there is at least some clarity:
this.Project.Message
nsProject.Message
Project.Message
The 3 above examples are fairly clear now: the first has already been declared in the project, the second is the namespace and the third is probably a static method call.
Does any one have any comments about this approach; am I reinventing the wheel (are there already guidelines in place) or does any one have a different opinion on what can be done?
EDIT
Another reason for wanting to use Alias's is the current namespaces do not match (or have any significance in some places) to the folder structure. So not only do I want to ensure clarity between what type of object/namespace is being used, but my Alias will also be a guide as to the folder location. I know, this probably reads as hacking etc but (as per comments in this post) it is the first stage of many.
I wouldn't know of any "Official" guidelines, but whenever I alias a namespace I usually use a contraction of the Company and the Project. This would result in (using your example):
this.Project.Message.Send();
CompanyProject.Message.Send();
Project.Message.Send();
I prefer postfixing above hungarian btw (subjective I know).
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
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.
Are there any best-practices that state custom code shouldn't be placed in a System namespace? Should System and its children be reserved for Microsoft code?
I ask because I'm writing a class library that will be used across many projects and I'd like to keep things consistent by placing it in System.InteropServices (since it deals with P/Invoke).
It's not a good idea because it defeats one of the primary benefits of namespaces: preventing name clashes. What if a newer version of the framework introduced an identically named type in that namespace?
This is particularly bad for System namespaces since they are imported in many other pieces of code with using directives and introducing custom types in those namespaces pollutes the naming scope of other source files with unexpected identifiers.
To categorize your custom interop related types, you can create a new namespace like MyProduct.InteropServices.
If you place a new class in System.InteropServices, every file that has a using System.InteropServices; clause is forced to have your class in scope, which may confuse the programmer. Since the programmer cannot defend oneself against this, I'd consider this bad practise.
I disagree with everyone.
I think that in a limited subset of cases (mostly with extension methods) it is perfectly reasonable to place code in a system namespace.
Here is my side of the argument from an email thread we had debating Extension methods in the System namespace over at EPS:
Ok, so here's my side of the argument:
I really like to minimize code. That includes usings.
Yes, ReSharper picks up extension methods and adds the usings for you but some people don't have ReSharper, and besides, I prefer Coderush which as of yet does not actually (as far as I know) pick up extension namespaces.
There are at least two different types of extension methods; ones that are helper methods for our application - including domain and application-specific helpers, and ones that encapsulate features and syntax that we believe the language should have had to begin with.
A good example of the latter is the ability to do "a {0} {1}".Format("b", "c") or someListOfStrings.Join(", ") rather than having to do String.Join(someStringList.ToArray(), ", "). Other more debatable examples are IEnumerable<T>.ForEach and the IsNull() extension to take the place of the clumsy object.ReferenceEquals(null, someVar) syntax.
My argument is, that there is every reason to place this latter classification - your team broadly agrees should be in the language but aren't - in the appropriate namespace (System, System.IO, System.Linq, etc.). We want those functions to be available everywhere, just like we prefer the foreach and yield keywords to always be visible. If it is application-specific however it should go in its own namespace. 90% of the time application-specific helper extensions should likely not be extensions and not even be static. I exclude from this statement using extension methods to provide aliases for function names.
You can get in some trouble with this of course when calling into assemblies that contain system-wide extensions. Suppose that I was referencing the assembly containing my void IEnumerable<T>.ForEach method and wanted to create my own ruby-like R IEnumerable<T, R>.ForEach (which is actually just a Select, but nevermind that). This would be a problem! What I like to do to mitigate the issue is to define my extension classes as being internal so that they can be used only on my project. This solves the problem nicely.
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.