Well in short i am a big fan of writing nice looking code, there is a great article here
the beauty of doom 3 source code I have been using different code editors before visual studio.
And i liked a compact writing style.
I dont like almost empty white lines like
public void my function(string s)
{ //almost empty line
string n = domystuff();
if (n=="blanc")
{ //almost empty
mycode("should start a row earlier on { line");
} //..
else
{
ohno.notagain("another two blanc lines above and below else");
Altough.it.compiles("equaly");
myscreen.used = not.optimal;
}
}
If code is better written, then its nice to read, if something is nice to read with much white lines then the white lines spoil it. So i wonder can this auto-formatting be changed in VS2010 ?
C# as a language has a set of coding conventions which C# programmers expect to be fairly consistent from project to project. If you want to use the One True Brace style, switch to Java.
If you insist on being the odd man out, you can configure the Visual Studio auto-formatter in Tools → Options... → Text Editor → C# → Formatting.
Related
I really like the new Visual Studio 2015, but the auto formatting is a bit too much extensive for my liking. Especially I like to have control over whitespace:
public class TipStats
{
public int Points { get; set; }
public int Position { get; set; }
public decimal Percentage { get; set; }
}
I only see three autoformat settings in my settings, and I have ticked them all off - still Visual Studio is autoformatting my whitespace.
Are there any other hidden settings that I need to know for disabling all whitespace autoformatting?
Update
As #Saragis notes Ignore spaces in declaration statements works sometimes for this specific example, but still there all kind of autoformat forces working against what I want.
Most options seem to only define how you want your autoformatting. I'm looking for the setting that defines if you want autoformatting.
PS: I'm having only problems with autoformatting I still use CTRL+K, F to manual format parts of my code now and then.
Update - Added feature request on UserVoice
http://visualstudio.uservoice.com/forums/121579-visual-studio/suggestions/9795837-add-an-ignore-space-for-all-format-options
I realised I misunderstood the question in my original answer, so have added a partial answer disabling autoformatting for white space.
If you select ignore white space on all options where it is offered, it will not reformat the white space of those areas of code.
These screen shots are taken from VS2015 Enterprise.
I'm starting from the beginning to help anyone who lands here.
Go to Tools -> Options.
Scroll down to Text Editor. It's worth clicking through the all the general tabs. And the All languages tabs. There are some shared formatting settings that can be set, like line wraps.
Then go to the languages you wish to customise (I'm showing C#) and click on formatting. There you will find options, I have expanded the spacing one, as per the title of your question.
Then you can explore each of these tabs to customise your format for each language.
edit- since question has actually changed
To reduce the incidents of autoformatting, uncheck options like these:
The only way you can manage the autoformatting is to play with these settings.
You can also use regex with find and replace to remove space from files, but do so carefully.
Beyond these tips to customise your autoformatting, to reduce VS process of autoformatting and to manually autoformat, that's all I can think of.
There is also this:
Under Edit -> Advanced -> Delete Horizontal White Space
The answer from Yvette Colomb is fine, but it does neither work on declarations inside functions, nor on enums (where in my opinion it is needed most).
Thus I had the idea to just add a comment between the variable and the operator, which simply breaks the obvious rule "set exactly one space character between variable (or enum name) and operator (=)", because there is no operator following the variable any longer! Not very nice, but also not too bad and IMHO it has definitely more advantages than disadvantages. :-)
Disable virtual space
Virtual space is a headache, please disable it int Tool>Options>Text Editor>C#>General. Life is better.
For the last version of Visual Studio :
Go Preferences :
Go Source code > C# :
Set Policy to custom :
Go C# format and tap on edit :
Set like me the New Lines :
And voila.
Previously I am fairly certain that the "Encapsulate Field" command would turn something like the following:
public int SomeNumber;
into the following (what I want from VS 2015):
private int someNumber;
public int SomeNumber {
get { return someNumber; }
set { someNumber = value; }
}
but in Visual Studio 2015 I am seeing the following:
private int someNumber;
public int SomeNumber {
get {
return someNumber;
}
set {
someNumber = value;
}
}
Is there a way to fix this?
This was a design change in VS2015. In previous versions, the refactoring command paid attention to the Tools > Options > Text Editor > C# > Wrapping > "Leave block on single line" option. With it turned on, you'll get the property getter and setter body the way it encoded in the snippet, braces on the same line. The way you like it.
Different in VS2015, it now pays attention to the Tools > Options > Text Editor > C# > Formatting > New Lines > "Place open brace on new line for methods" setting. You get to choose between "egyptian" braces or having the opening brace separate. Neither of which you like.
Accidents happen when Microsoft creates new VS versions, this was not an accident. Whether this was done by "popular demand" is hard to reverse-engineer, I consider it pretty likely since this refactoring is usually done to write a non-trivial getter or setter, the kind that won't fit a single line. Providing us with a choice between all three possible formatting preferences looks like a problem to me, the existing formatting options are not a good match.
Only real option is to let Microsoft know that you are not happy with the change. There is an existing UserVoice article that proposes a change. You can vote for it or write your own. Post a link to it in your question so other SO users can vote.
Will that help you:
-Encapsulate Field Refactoring (C#):
https://msdn.microsoft.com/en-us/library/a5adyhe9.aspx
This website seems to offer a solution a the end of the topic.
Check also this post :
-Different Refactoring style for field encapsulation: how to make Visual Studio change it?
Different Refactoring style for field encapsulation: how to make Visual Studio change it?
This one is corresponding to your question in a certain manner: the question is really related to yours :)
I myself have tried changing the snippet file to suite my file but VS doesn't take effect. What I end up doing is
Encapsulate the fields as usual.
Copy and paste the code into notepad++ and do a Find and Replace.
Find:
(\{)*(\s*)*(get|set)\r\n\s+{\r\n\s+(.*)\r\n\s+\}\s+
Replace with:
$1$3\{$4\}
Paste the result back into VS. VS will format it follow the "Leave block on single line".
I was typing a switch with an enum in VS 2013 and all case statements filled out automatically after I finished the switch. Now I can't repeat it. I was not hallucinating, the switch filled out with all enum options, one per case, automatically. Looked through MS docs for VS 2013 and didn't find it.
I use quite a few enums and this feature will save me a ton of time if I can find what it is I did to trigger it. Can anyone help?
Notice: This answer applies to performing the switch/enum autogeneration while also using Resharper.
Using Visual Studio 2013 and Resharper 8.2, the previously mentioned methods do not work. Here's how to actually get this generation to work when using Resharper. Hopefully it will save someone the fifteen minutes I just spent figuring this out.
Performing "sw(tab)(tab)" will only generate the following:
switch (nameOfEnumVariable)
{
}
Resharper can generate the labels using Alt + Enter (if your cursor stands in the switch statement) and selecting Generate switch labels as in the following screenshot:
The result looks like this:
Type "sw", and then press tab,tab.
The selected answer is mostly correct, you don't need Resharper as other's have suggested (at least not with Visual Studio Professional 2012+).
1) type "sw" then "[tab][tab]" (as Marvin Smit said)
Which (as jmblack said) will generate something like:
switch (switch_on)
{
default:
}
but then
2) you need to select which thing to enumerate on (switch_on will be highlighted still at this point). So type in the Enum (or your variable of the enum type) while switch_on is highlited and hit [Enter][Enter].
(I just confirmed this worked on my machine running VS2012, and i'm fairly certain this is the same thing i have done on my other machine running VS2013, and i haven't tested other versions of VS (ultimate/express/etc.))
Visual studio 2017, 2019 - without Resharper:
1) write "switch"
2) press two times TAB, then you will see:
switch (switch_on)
{
default:
}
(the switch_on is highlited)
3) retype switch_on to your enum variable or type
4) press ENTER or click somewhere else (pressing TAB does not work), now you should see all the enum items filled:
switch (YOUR_ENUM_VARIABLE_OR_TYPE)
{
case YOUR_ENUM_TYPE.Item1:
break;
case YOUR_ENUM_TYPE.Item2:
break;
case YOUR_ENUM_TYPE.Item3:
break;
default:
break;
}
I think what you need is this:
sw(tab)(tab)enumVariableName(tab)(downArrow)
I tested it and works ( in VS2013 at least).
By default, Visual Studion's snippet works correct. You should type "sw" and then press double "Tab".
If you use Resharper, the snippet doesn't work, because Resharper's snippet has more priority, by default. So, you should turn off resharper's snippet.
Go to "Resharper" -> "Template Explorer"-> "C#" then uncheck "switch". Try "sw" + double "Tab"
I've written a free and open source extension, based on Roslyn, for Visual Studio 2015 and 2017, that not only allows to fill the switch case for an enum, but is also capable of adding new cases if enum values (fields) have been added to the enum type definition, or sort the list of cases by value or name.
It's available here: Enum Case Generator
This is how to use it:
VS 2019 + resharper create an empty switch with your variable. Click on first curly bracket "{" Then press alt + enter You will see Generate switch labels. Screenshot below:
Hi I just ran into the same problem, I just found out that when you do:
switch(nameofvariable){
default:
break;
}
when you are filling the variable and you double click on the variable of your choice (the enum) it will give you all the cases
In Visual Studio (I'm using 2012), is there any way of editing the way that Ctrl-K-D combinations handles its Auto-Formatting?
I don't mean changing what these key combinations do, I mean extending the way the auto-formatting is done.
The way it handles tabbing, etc are fine, I'm more concerned with white-space.
We're using a plugin that makes it easy to align variable properties, making them easy to read. Like so:
var test = 'whatever',
another = 'this one',
alignedProperly = 'yay';
Seems nitt-picky yes, but in really large Object literals it's so helpful to be able to read them!
Has anyone found where the rules for auto-formatting are located, and if they can be edited/changed? (Can't find them anywhere in the options!)
Are you looking for:
Tools > Options > Text Editor > C# > Formatting > Spacing > Set other
spacing options > Ignore space in declaration statements
This is in VS 2010, but i guess 2012 should be somewhat similar.
In VS 2017:
Tools > Options > Text Editor > C# > Code Style > Formatting > Spacing > Set other spacing options > Ignore space in declaration statements
This functionality has been changed to Ctrl+K, Ctrl+E.
This is called Code Cleanup.
Click on the "duster" on the bottom of VS page and click "Configure Code Cleanup" to assign specific actions.
Code Cleanup
Note to Googlers, this question is somewhat out of date as the requested feature is now supported in the current version of ReSharper 2017.3.1
I like to formatting my code to align right side of equal operands.
Like here:
bool canRead = false;
bool canReadClass = true;
string className = boType.Name;
I've switch to ReSharper recently and found it very useful but cannot find option allowing me format code in described way.
Do you know if there is such option / plugin?
Maybe you know other than ReSharp solution allowing that?
EDIT:
How to decide what part of code shall be aligned?
My convention is aligning all variables in same block.
By "block" I meant part of code not divided by empty lines.
eg
// First block
int count = 10;
string name = "abc";
bool calculate = true;
.....
.....
// Second block
MyOwnType myType = new MyOwntype();
int count = 10;
EDIT -2
I've opened R# ticket for this. If anyone interested please vote!
There is (currently) no way to do this out of the box in ReSharper. Fortunately, ReSharper has a very rich extensibility API (albeit poorly documented). I've spent a lot of time with Reflector trying to figure things out.
We use a similar alignment guideline for class members in a company I work for (to the extreme, we also align method parameters). I wrote a plugin for ReSharper to help me do just that. It's a "Code Cleanup" module, which runs sometime during the code cleanup (Ctrl-E, Ctrl-F) and aligns the code for you. It also makes the class sealed, if possible.
Some examples:
Method parameters:
public void DoSomething(string name,
int age,
IEnumerable coll)
(you will need to change Wrap formal parameters to Chop always in Options->Formatting Style->Line Breaks and Wrapping for this to work properly)
Constants:
private const int RESOURCEDISPLAYTYPE_DOMAIN = 0x00000001;
private const int CONNECT_COMMANDLINE = 0x00000800;
private const int CONNECT_INTERACTIVE = 0x00000008;
private const string RESOURCE_NAME = "Unknown";
You can download the source code from my SkyDrive.
Edit I seem to have lost access to that SkyDrive, and lost the files too. This was before github :(
Please note that you'll need several things to compile/debug it:
Update the Command Line Arguments
in Debug tab in Project
Properties with the correct path of
the output DLL:
/ReSharper.Plugin
"X:\<projects>\MyCompany.CodeFormatter\MyCompany.CodeFormatter\bin\Debug\MyCompany.CodeFormatter.dll"
This allows debugging the plugin via
F5, and it will be
automatically installed in
ReSharper's Plugins in the new
Visual Studio instance which will
open.
The plugin is for ReSharper 4.5 and it references the DLLs of this version. If you installed ReSharper anywhere else except C:\Program Files\JetBrains\ReSharper, you will have to fix the references.
This does not align variables inside methods, but it shouldn't be hard to add :)
After you install this, just run Code Cleanup to fix your alignment (I never got a reply from JetBrains about how to do this during brace/semicolon formatting, unfortunately).
Assembly was renamed to protect the innocent :)
Good luck!
I think it is worth noting that the Visual Studio Productivity Power Tools have an Align Assignments feature.
Here's a link to the Visual Studio 2013 Productivity Power Tools.
You can try this: Code Alignment
It supports
Align by... (Dialog)
Align by position... (Dialog)
Align by Equals
Align by m_
Align by "
Align by .
Align by Space
Productivity Power Tools 2012 also has a command for this: ctrl-alt-]
Other goodies are obviously there as well.
As far as I know, this is unfortunately not possible using Resharper.
Years late, but further to the comment from #MickyD, Resharper can do this for you, see Resharper blog. Go to Resharper/ Options/ Code Editing/ C#/ Tabs, Indents, Alignment. Scroll to the bottom of the options in the right hand window pane to find "Align Similar Code in Columns", click things, enjoy.