Why remove unused using directives in C#?

Solution 1:

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!

Solution 2:

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

Solution 3:

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;.