6
votes

I like to adhere to StyleCop's formatting rules to make code nice and clear, but I've recently had a problem with one of its warnings:

All using directives must be placed inside of the namespace.

My problem is that I have using directives, an assembly reference (for mocking file deletion), and a namespace to juggle in one of my test classes:

using System;
using System.IO;
using Microsoft.Moles.Framework;
using Microsoft.VisualStudio.TestTools.UnitTesting;
[assembly: MoledType(typeof(System.IO.File))]

namespace MyNamespace
{
//Some Code
}

The above allows tests to be run fine - but StyleCop complains about the using directives not being inside the namespace.

Putting the usings inside the namespace gives the error that "MoledType" is not recognised.

Putting both the usings and the assembly reference inside the namespace gives the error

'assembly' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'type'. All attributes in this block will be ignored.

It seems I've tried every layout I can but to no avail - either the solution won't build, the mocking won't work or StyleCop complains!

Does anyone know a way to set these out so that everything's happy? Or am I going to have to ignore the StyleCop warning in this case?

3
If you give the fully qualified name for MoledType and move just the usings into the namesapce does it still comaplain?Leom Burke
Yup that fixed it! I got this comment just after I submitted the answer to my own question haha! Thanks though Leom, much appreciated =)Jack

3 Answers

11
votes

Solved two minutes later!

I just needed to put the full path of "MoledType" in the assembly reference - meaning I could leave it outside of the namespace with the using directives inside like so:

[assembly: Microsoft.Moles.Framework.MoledType(typeof(System.IO.File))]
namespace MyNamespace
{
using System;
using System.IO;
using Microsoft.Moles.Framework;
using Microsoft.VisualStudio.TestTools.UnitTesting;

// Some Code...
}

Hopefully someone'll find this useful!

6
votes

The typical pattern would be to put all of your Assembly level attributes within the AssemblyInfo.cs file. Typically this file does not have any namespace element at all and all of the assembly attributes are defined using fully qualified names.

1
votes

Agreed with Jason, you should put this in the AssemblyInfo.cs instead (Project -> Properties).

But! Be careful with what you put in the AssemblyInfo.cs file. Say you want to use:

[assembly: InternalsVisibleTo("ClassA")]

If you put this in AssemblyInfo.cs, ALL internal classes of the project will be visible to ClassA. This is not always wanted.