Why remove unused using directives in C#? - c#

I'm wondering if there are any reasons (apart from tidying up source code) why developers use the "Remove Unused Usings" feature in Visual Studio 2008?

There are a few reasons you'd want to take them out.
It's pointless. They add no value.
It's confusing. What is being used from that namespace?
If you don't, then you'll gradually accumulate pointless using statements as your code changes over time.
Static analysis is slower.
Code compilation is slower.
On the other hand, there aren't many reasons to leave them in. I suppose you save yourself the effort of having to delete them. But if you're that lazy, you've got bigger problems!

I would say quite the contrary - it's extremely helpful to remove unneeded, unnecessary using statements.
Imagine you have to go back to your code in 3, 6, 9 months - or someone else has to take over your code and maintain it.
If you have a huge long laundry list of using statement that aren't really needed, looking at the code could be quite confusing. Why is that using in there, if nothing is used from that namespace??
I guess in terms of long-term maintainability in a professional environment, I'd strongly suggest to keep your code as clean as possible - and that includes dumping unnecessary stuff from it. Less clutter equals less confusion and thus higher maintainability.
Marc

In addition to the reasons already given, it prevents unnecessary naming conflicts. Consider this file:
using System.IO;
using System.Windows.Shapes;
namespace LicenseTester
{
public static class Example
{
private static string temporaryPath = Path.GetTempFileName();
}
}
This code doesn't compile because both the namespaces System.IO and System.Windows.Shapes each contain a class called Path. We could fix it by using the full class path,
private static string temporaryPath = System.IO.Path.GetTempFileName();
or we could simply remove the line using System.Windows.Shapes;.

This seems to me to be a very sensible question, which is being treated in quite a flippant way by the people responding.
I'd say that any change to source code needs to be justified. These changes can have hidden costs, and the person posing the question wanted to be made aware of this. They didn't ask to be called "lazy", as one person inimated.
I have just started using ReSharper, and it is starting to give warnings and style hints on the project I am responsible for. Amongst them is the removal of redundant using directive, but also redundant qualifiers, capitalisation and many more. My gut instinct is to tidy the code and resolve all hints, but my business head warns me against unjustified changes.
We use an automated build process, and therefore any change to our SVN repository would generate changes that we couldn't link to projects/bugs/issues, and would trigger automated builds and releases which delivered no functional change to previous versions.
If we look at the removal of redundant qualifiers, this could possibly cause confusion to developers as classes in our Domain and Data layers are only differentiated by the qualifiers.
If I look at the proper use of capitalisation of anachronyms (i.e. ABCD -> Abcd), then I have to take into account that ReSharper doesn't refactor any of the Xml files we use that reference class names.
So, following these hints is not as straight-forward as it appears, and should be treated with respect.

Less options in the IntelliSense popup (particularly if the namespaces contain lots of Extension methods).
Theoretically IntelliSense should be faster too.

Remove them. Less code to look at and wonder about saves time and confusion. I wish more people would KEEP THINGS SIMPLE, NEAT and TIDY.
It's like having dirty shirts and pants in your room. It's ugly and you have to wonder why it's there.

Code compiles quicker.

Recently I got another reason why deleting unused imports is quite helpful and important.
Imagine you have two assemblies, where one references the other (for now let´s call the first one A and the referenced B). Now when you have code in A that depends on B everything is fine. However at some stage in your development-process you notice that you actually don´t need that code any more but you leave the using-statement where it was. Now you not only have a meaningless using-directive but also an assembly-reference to B which is not used anywhere but in the obsolete directive. This firstly increases the amount of time needed for compiling A, as B has to be loaded also.
So this is not only an issue on cleaner and easier to read code but also on maintaining assembly-references in production-code where not all of those referenced assemblies even exist.
Finally in our exapmle we had to ship B and A together, although B is not used anywhere in A but in the using-section. This will massively affect the runtime-performance of A when loading the assembly.

It also helps prevent false circular dependencies, assuming you are also able to remove some dll/project references from your project after removing the unused usings.

At least in theory, if you were given a C# .cs file (or any single program source code file), you should be able to look at the code and create an environment that simulates everything it needs. With some compiling/parsing technique, you may even create a tool to do it automatically. If this is done by you at least in mind, you can ensure you understand everything that code file says.
Now consider, if you were given a .cs file with 1000 using directives which only 10 was actually used. Whenever you look at a symbol that is newly introduced in the code that references the outside world, you will have to go through those 1000 lines to figure out what it is. This obviously slows down the above procedure. So if you can reduce them to 10, it will help!
In my opinion, the C# using directive is very very weak, since you cannot specify single generic symbol without genericity being lost, and you cannot use using alias directive to use extension methods. This is not the case in other languages like Java, Python and Haskell, in those languages you are able to specify (almost) exactly what you want from the outside world. But even then, I will suggest to use using alias whenever possible.

Related

C# Resource Files

My resources are stored in an assembly of their own, and I have a reference to that assembly in my web app. I am able to access resources in two different ways - via compiled constants or by using a ResourceManager.
var method1 = Prototype.Localization.CustomerRecord.BillingId;
or
var resx = new ResourceManager(typeof (Prototype.Localization.CustomerRecord));
var method2 = resx.GetString("BillingId");
Using the first approach seems like a no brainer (but that generally means it's going to come back and bite me when things get more complicated), so what are the advantages or disadvantages to the second approach? Is the first approach going to cause me issues down the road?
So what are the advantages or disadvantages to the second approach?
2nd approach is what resx compiler does under the cover. IMO 2nd one is always worse because you have a string (then it may goes detached and you won't know until run-time) and because of that you'll lack of compile-time checks and design-time support.
Is the first approach going to cause me issues down the road?
No, at least no more than anything else (because you'll catch errors in your HTML pages when you'll first compile them at run-time).
So I may ask: if first approach is shorter and easier then is there any good reason to use the 2nd one? My answer is "no" (moreover you can mix them, in case you'll need it for a special thing).
Yeah, I agree with Adriano that the 2nd is worse because of those "Magic" strings.
The first approach you have some more advantages that would include compile time check, since you reference a class and a property if this property doesn't exist you will get an error back, intellisense is another one.
Another advantage, is that if you decided to move away from the built in resource manager, you could just replace the generated class (resource class) by your own respecting the namespace and so on, with your own internal logic.
IMO, I would stick with the first one.

Will the compiler only compile code that can get executed?

I have a class library and am using only part of it. Is there a need to delete what isn't being used in order to shrink the size of the created code (in release configuration)?
As far as I've seen, the compiler takes care of that, and removing the code doesn't change the EXE file size. Will this always be true? Removing all unneeded code would take very long, so I want to know if there's need for that.
More information: there are methods and classes in the class library that aren't called from the executing code, but are referenced by other parts of code in the class library (which themselves are never called).
No, the compiler includes the "dead" code as well. A simple reason for this is that it's not always possible to know exactly what code will and won't be executed. For example, even a private method that is never referenced could be called via reflection, and public methods could be referenced by external assemblies.
You can use a tool to help you find and remove unused methods (including ones only called by other unused methods). Try What tools and techniques do you use to find dead code? and Find unused code to get you started.
It all gets compiled. Regardless of whether it is called or not. The code may be called by an external library.
The only way to make the compiler ignore code is by using Compiler Preprocessor Directives. More about those here.
I doubt the compiler will remove anything. The fact is, the compiler can't tell what is used and what is not, as types can be instantiated and methods called by name, thanks to reflection.
Let's suppose there is a class library called Utility. You created a new project and added this class library to that project. Even if your EXE calls only 1-2 methods from the class library, it's never a good idea to delete the unreferenced code.
It would go against the principle of reusablity. Despite the fact that there would be some classes present in the library unreferenced from the EXE, it would not have any bad impact on performance or size of the program.
Determining all and only dead code is (if one makes the idealization that one has a "math world" like language) recursively undecidable, in most languages. (A few rare ones like the Blaise language are decidable.)
to the question of whether there is a "need to delete what isn't being used in order to shrink the size of the created code": i think this would only be useful to save network bandwidth. removing unused code is crucial in web applications to improve loading speeds etc.
if you're code is an exe or a library, the only reason i see to remove dead code, is to improve your code quality. so that someone looking at your code 2 years down the line won't scratch their heads wondering what it does.

Resharper and Namespace alias qualifier

I've searched around a bit for this and tried a few things and can't get it to work without turning some stuff off that I want on.
Normally I let Resharper have its way with namespace optimizations. In a Service implementation that's mapping DTO's to Domain Model objects it's a nice visual to create an alias for each. That way when it's late and you're sleep deprived seeing Dtos.Customer and DomainModel.Customer helps.
using DomainModel = MyProduct.Core.Domain.Model;
using Dtos = MyProduct.ServiceModel.Dtos;
When I run code cleanup it changes those to:
using DomainModel = MyProduct.Core.Domain.Model;
using Customer = MyProduct.Core.Domain.Model.Customer;
Does anyone do this or something similar and keep R# from whacking it?
This is something ReSharper will do when you let it: shorten references, on code cleanup.
Even though this behavior might be unwanted for you, it's technically seen correct. Because in your code it'll shorten something. And that's what the algorithm is supposed to do.
This is how the algorithm works that causes this result:
Resharper finds a reference that can be made shorter (you've not given me enough code to exactly tell you where, but that doesn't matter).
After shortening it needs to assure that the object can be resolved, so it adds a new using for it (using Customer = MyProduct.Core.Domain.Model.Customer; in your case).
Resharper detects that using Dtos = MyProduct.ServiceModel.Dtos; is no longer in use (after all, the other using covers your shortened reference). And removes it.
This is what I suspect is causing this. I cannot be 100% certain without seeing the actual usages in code. But this is most likely the cause of the refactoring.

Is it worth removing "using System" from my files?

Developing a series of POCOs on my project, and just realized that some of them doesn't need the using System; clause.
Is there any performance or size penalty for leaving unused using <module>; on my objects or project ?
Will my classes get bigger, or slower, or bloated because of this or the compiler/optimizer is smart enough to take care of this?
no there are not performance issue .
it is just a readability matter(I would suggest to remove them)
more info at:
Why should you remove unnecessary C# using directives?
All the "using System;" statement does is allow you to use that namespace without fully qualified names. It doesn't affect run-time performance in any way.
There is no runtime performance penalty for having unused using statements in your code. They don't appear is the compiled DLL in any form (they do exist in the PDB).
However if you know them to be invalid it's generally considered good style to remove them. Having unused usings is essentially stating a false dependency your code has on a set of types and extension methods.
Determining which usings are not used is a tedious process. I find it's best to just install a tool like PowerCommands and let it do the work on file save.
http://visualstudiogallery.msdn.microsoft.com/e5f41ad9-4edc-4912-bca3-91147db95b99
That brings neither performance gain nor hit.
I remove all unused and sort all used usings as code style (neatness). You can do this via Visual Studio context menu (I bound it to a hotkey).
If you are not using a reference / assembly or extended functionality
for example using System.Linq; by default gets added to VS2010 projects.. if you don't use it.. just remove it.. no performance issues
The using directive is just syntactic sugar.
Adding using references will not affect performance other than a marginal compile-time difference.
It in no way affects the output of the compiler or the performance of the compiled program!
It can be removed a as part of personal preference. I would personally recommend it as it would make the compilation faster (fewer namespaces for the compiler to look up) and also improve the performance of intellisense.
It has no impact on performance. It can be kept or removed at your discretion.
However, consider keeping it. The System namespace contains the most commonly used parts of the .NET Framework, and at some point during the lifetime of your file, you (or someone) will probably end up needing it. That means inevitably putting it back, possibly after wasting time wondering why none of the system classes exist.

Why should you remove unnecessary C# using directives?

For example, I rarely need:
using System.Text;
but it's always there by default. I assume the application will use more memory if your code contains unnecessary using directives. But is there anything else I should be aware of?
Also, does it make any difference whatsoever if the same using directive is used in only one file vs. most/all files?
Edit: Note that this question is not about the unrelated concept called a using statement, designed to help one manage resources by ensuring that when an object goes out of scope, its IDisposable.Dispose method is called. See Uses of "using" in C#.
There are few reasons for removing unused using(s)/namespaces, besides coding preference:
removing the unused using clauses in a project, can make the compilation faster because the compiler has fewer namespaces to look-up types to resolve. (this is especially true for C# 3.0 because of extension methods, where the compiler must search all namespaces for extension methods for possible better matches, generic type inference and lambda expressions involving generic types)
can potentially help to avoid name collision in future builds when new types are added to the unused namespaces that have the same name as some types in the used namespaces.
will reduce the number of items in the editor auto completion list when coding, posibly leading to faster typing (in C# 3.0 this can also reduce the list of extension methods shown)
What removing the unused namespaces won't do:
alter in any way the output of the compiler.
alter in any way the execution of the compiled program (faster loading, or better performance).
The resulting assembly is the same with or without unused using(s) removed.
It won't change anything when your program runs. Everything that's needed is loaded on demand. So even if you have that using statement, unless you actually use a type in that namespace / assembly, the assembly that using statement is correlated to won't be loaded.
Mainly, it's just to clean up for personal preference.
Code cleanliness is important.
One starts to get the feeling that the code may be unmaintained and on the browfield path when one sees superfluous usings. In essence, when I see some unused using statements, a little yellow flag goes up in the back of my brain telling me to "proceed with caution." And reading production code should never give you that feeling.
So clean up your usings. Don't be sloppy. Inspire confidence. Make your code pretty. Give another dev that warm-fuzzy feeling.
There's no IL construct that corresponds to using. Thus, the using statements do not increase your application memory, as there is no code or data that is generated for it.
Using is used at compile time only for the purposes of resolving short type names to fully qualified type names. Thus, the only negative effect unnecessary using can have is slowing the compile time a little bit and taking a bit more memory during compilation. I wouldn't be worried about that though.
Thus, the only real negative effect of having using statements you don't need is on intellisense, as the list of potential matches for completion while you type increases.
You may have name clashes if you call your classes like the (unused) classes in the namespace. In the case of System.Text, you'll have a problem if you define a class named "Encoder".
Anyways this is usually a minor problem, and detected by the compiler.
Leaving extra using directives is fine. There is a little value in removing them, but not much. For example, it makes my IntelliSense completion lists shorter, and therefore easier to navigate.
The compiled assemblies are not affected by extraneous using directives.
Sometimes I put them inside a #region, and leave it collapsed; this makes viewing the file a little cleaner. IMO, this is one of the few good uses of #region.
if you want to maintain your code clean, not used using statements should be removed from the file. the benefits appears very clear when you work in a collaborative team that need to understand your code, think all your code must be maintained, less code = less work, the benefits are long term.
Your application will not use more memory. It's for the compiler to find classes you use in the code files. It really doesn't hurt beyond not being clean.
It’s personal preference mainly. I clean them up myself (ReSharper does a good job of telling me when there’s unneeded using statements).
One could say that it might decrease the time to compile, but with computer and compiler speeds these days, it just wouldn’t make any perceptible impact.
They are just used as a shortcut. For example, you'd have to write:
System.Int32 each time if you did not have a using System; on top.
Removing unused ones just makes your code look cleaner.
The using statement just keeps you from qualifying the types you use. I personally like to clean them up. Really it depends on how a loc metric is used
Having only the namespaces that you actually use allows you to keep your code documented.
You can easily find what parts of your code are calling one another by any search tool.
If you have unused namespaces this means nothing, when running a search.
I'm working on cleaning up namespaces now, because I'm constantly asked what parts of the application are accessing the same data one way or another.
I know which parts are accessing data each way due to the data access being separated by namespaces e.g. directly through a database and in-directly through a web service.
I can't think of a simpler way to do this all at once.
If you just want your code to be a black box (to the developers), then yes it doesn't matter. But if you need to maintain it over time it is valuable documentation like all other code.
The 'using' statement does not affect performance as it is merely a helper in qualifying the names of your identifiers. So instead of having to type, System.IO.Path.Combine(...), you can simply type, Path.Combine(...) if you have using System.IO.
Do not forget that the compiler do a lot of work to optimize everything when building your project. Using that is used in a lot of place or 1 shouldn't do a different once compiled.

Categories

Resources