Domanda

When I create a new class file in C#, the usual structure is as follows:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace UnitTest
{
    class Class1
    {
    }
}

StyleCop doesn't like having using directives outside of the namespace, so ideally, I would refactor my code as such:

namespace UnitTest
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;

    class Class1
    {
    }
}

From my days as a Java programmer, I was taught that it was better to import only the references that were necessary, rather than the entire package like so:

import foo.bar.MyObject;

instead of

import foo.bar.*;

I know that this can also be done in C#, with the added feature that you can use aliases for types (sometimes useful when working though native code):

using StringBuilder = System.Text.StringBuilder;

or when using aliases:

using HANDLE = System.IntPtr;
using HDC = System.IntPtr;

So my questions, regarding best practice and efficiency of using directives:

  1. Is is more efficient to keep using statements inside a namespace, or is this purely a stylistic preference?
  2. If is more efficient to only include the necessary items, as opposed to the entire namespace?
È stato utile?

Soluzione

  1. There are some fringe cases where it makes a difference but for the majority of cases it is just a stylistic preference.
  2. The using statements just tell the compiler where it can locate the types. It has no influence on the runtime.

Altri suggerimenti

  1. nope; stylistic preference, as long as it doesn't introduce any semantic changes; the cases where it changes the meaning are very rare (although there used to be a bug with the LINQ-to-SQL code generator that did care about where you put them - this is now fixed)
  2. nope; unused directives are not used, and they don't massively impact the compiler

Note that having too many directives can cause ambiguities; for example there are a myriad of classes called Timer. For that reason it is worth keeping things tidy.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top