How to quickly format a C# class file – Ctrl-K, Ctrl-D

In C# as you are typing in a class file the indenting of your code can easily get out of alignment making the code hard to read.  Where does your class, if block, or method begin and end??

image

You can manually go and fix each line but there is a much simpler way to correct the indenting.  You can use Ctrl-K, Ctrl-D to format the entire document.  Now your code will be reformatted to the correct indenting for your page.

image

Couple things to note:

  • If there are errors in the structure of your code (missing closing brackets, missing semi-colon, etc.) then this will not work.  This will still work with other errors such as undeclared variables.
  • If you are working on legacy code (for example fixing a bug) and there is a different indenting structure, it is good practice to stick with the legacy indenting and not modify the indenting of the entire file just because you fixed a bug in one line of code.  You should try to minimize your code change to only what was necessary to fix the bug (don’t reformat the entire file).  The next person that does a diff on your check-in with the previous check-in will thank you.
  • I also leave the Visual Studio indentation settings alone and stick with the defaults.  If you have a different indentation style than a code file that was previously checked, this process could also cause the subsequent diff to show lots of red. 
  • You can use Ctrl-K, Ctrl-F on smaller blocks of text, so if you have a strange indenting style then highlighting only your change can correct the indentation on the selected lines and not the entire file.
  • These can be found under the Edit > Advanced Menu:
    • image
  • Cutting and Pasting is also another way to get the content formatted quickly:
    • Ctrl-A, Ctrl-X, Ctrl-V


Published 21 October 2009 08:57 PM by Jeff Widmer

Comments

# MuteThis said on 21 October, 2009 11:43 PM

I think deleting and adding a curly brace back will do the same thing.

# AndrewSeven said on 22 October, 2009 09:33 AM

Another option is to map it to a simple keystroke like CTRL+Q

# OWScott said on 24 October, 2009 11:54 PM

That shortcut is Ctrl E, Ctrl D for me.  I'm pretty sure I chose the C# development environment.  It sounds like it must be different depending on which environment type is chosen.

Leave a Comment

(required) 
(required) 
(optional)
(required) 

Search

Go

This Blog

News

    Ads by Lake Quincy Media
    Ads by Lake Quincy Media

Recommended Blogs

Syndication