Search code examples
c#usingusing-directives

Is there a way to group "using" directives in a separate file?


Say you have some boiler plate using statements. Say something like this:

#if !NUNIT
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Category = Microsoft.VisualStudio.TestTools.UnitTesting.DescriptionAttribute;
#else
using NUnit.Framework;
using TestClass = NUnit.Framework.TestFixtureAttribute;
using TestMethod = NUnit.Framework.TestAttribute;
using TestInitialize = NUnit.Framework.SetUpAttribute;
using TestCleanup = NUnit.Framework.TearDownAttribute;
using TestContext = System.Object;
#endif

(This is for my unit testing code) If I did not want to put that in the top of every file that has unit tests, is there a way to setup a level of indirection here?

I don't think this would work, but here is an example of what I am thinking of:

Make a file called NUnitCompatability.cs and put the above code in it. Then add using NUnitCompatability to all my unit test files. This would work in Delphi, but not in C# (I think). But is there another way to get to this type of functionality?


Solution

  • No, this is not possible.

    You are probably thinking of using directives as if they were similar to an #include in C. This is not the case.

    A using directive only tells the compiler in which namespaces to search for the types used in a specific file. Therefore you are also not able to store them in a separate file.

    I wouldn't bother to put conditional compiler directives in my code for using directives. There is almost no overhead related to unused usings at compile time (the search space is slightly larger) and no overhead at all at runtime.