Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to force indentation of C# conditional directives?

is there an option how to disable that #if, #endif and other directives are not indended after Edit -> Advanced -> Format document in Visual Studio?

Thank you!

like image 358
Martin Vseticka Avatar asked Aug 24 '09 08:08

Martin Vseticka


3 Answers

Look at StyleCop.

StyleCop analyzes C# source code to enforce a set of style and consistency rules. It can be run from inside of Visual Studio or integrated into an MSBuild project. StyleCop has also been integrated into many third-party development tools.

You can even add custom rules: Creating Custom Rules for Microsoft Source Analyzer

Hope it helps.

like image 189
pero Avatar answered Nov 07 '22 10:11

pero


I'm afraid there's no direct setting in Visual Studio. For C#, this is tracked by Roslyn issue 12306, which was opened in mid-2016 and remains open as of late 2021 (Visual Studio has offered a similar option for C/C++ since 2015).

As an alternative, you might try to use an external tool to format your code (e.g. AStyle). You could create a macro in VS that closes the current file, runs the external tool on the file and re-opens it (and maybe re-positions the cursor at the previous position), so you would be able to format your code from Visual Studio.

I'm not sure if the task is worth the effort, anyway...

Otherwise, you might write your own macro to indent the preprocessor directives in the current file after it has been formatted by VS, without even using external tools (which would probably be rather painful to configure in order to obtain exactly the same formatting as in VS).

like image 35
Paolo Tedesco Avatar answered Nov 07 '22 11:11

Paolo Tedesco


You could hide it away in a static helper class somewhere.

internal class Helper
{
    internal static bool IsDebugBuild
    {
        get
        {
#if DEBUG
            return true;
#endif
            return false;
        }
    }
}

Then you can just use it as below:

if (Helper.IsDebugBuild)
{
    ...
}
like image 3
Craig Avatar answered Nov 07 '22 10:11

Craig