views:

91

answers:

3

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?

+4  A: 

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.

0xA3
If the namespace is not available (due to a missing assembly reference), you will get a compile error. That's likely what he's trying to avoid here (different behavior based on presence of NUnit)
Bob
+2  A: 

There is no built-in support for this in C#. The C# preprocessor is intentionally a very limited tool and does not support #include style operations where you could make one file out of two.

Yes for very simple cases like this it can be a tad bit frustrating. But it outweighs the evil that so many people have done, and continue to do, with the C++ preprocessor.

JaredPar
+2  A: 

If you have a particular set of using statements you would like to use for unit testing classes, it seems that this would be good reason to make a new template specifically for the purpose. You are not limited to the file types that VS provides -- you can extend them to make your own, in which you can put your own selection of using statements. It would take too long to describe the process here, so check MSDN here:

http://msdn.microsoft.com/en-us/library/6db0hwky(v=VS.100).aspx

Cyberherbalist