Friday, July 26, 2019

c# - Stop Visual Studio from putting using directives outside namespace




Is there a setting in Visual Studio (or Resharper) that allows you to specify what namespaces should be default and which scope they are put in?



The default for an MVC project for example is



using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace Namespace

{
public class Class1
{
}
}


but Resharper and Stylecop complain:





All using directives must be placed inside of the namespace. [StyleCop Rule: SA1200]
Using directive is not required by the code and can be safely removed




Is there a way to make the default simply:



namespace Namespace
{
public class Class1
{
}

}

Answer



Generally I don't believe there's any harm in including using statementents at the top of your class. I actually find it easier to include them there, so it's up to you whether you want to respect that rule.



If you do however, all of the file templates are available and can be edited. See the answer How do I edit the Visual Studio templates for new C# class/interface? to detail where they live on each Visual Studio version.



Once you're there you can change the layout, so for example a basic class looks like:



using System;

using System.Collections.Generic;
$if$ ($targetframeworkversion$ >= 3.5)using System.Linq;
$endif$using System.Text;
$if$ ($targetframeworkversion$ >= 4.5)using System.Threading.Tasks;
$endif$
namespace $rootnamespace$
{
class $safeitemrootname$
{
}

}


You could change this to the following or similar:



namespace $rootnamespace$
{
using System;
using System.Collections.Generic;
$if$ ($targetframeworkversion$ >= 3.5)using System.Linq;

$endif$using System.Text;
$if$ ($targetframeworkversion$ >= 4.5)using System.Threading.Tasks;
$endif$

class $safeitemrootname$
{
}
}



There may be quite a few files to change though!


No comments:

Post a Comment

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...