How to format alignment of C# class file

| July 14, 2010 | 0 Comments

While working with C# class files be it Windows Application or Web Application or anyone where you need to work with C# class files, sometimes the indenting or alignment of that class files get distorted. Then it all makes reading and understanding of code confusing.

Distorted alignment Code Snippet:

private void btnSubmit_Click(object sender, EventArgs e)
        {
            if (txtName.Text != String.Empty)
            {
                  lblClientName.Text = txtName.Text;
}
            else
            {
                lblError.Text = "Blank fields not allowed.";
            }}

So what you do in these situation? Manually try to set each and every braces at correct position. All this waste your worthy time in worst things. Here is the solution to avoid such in future. Use Ctrl-K, Ctrl-D consecutively to format entire document. Or alternatively you can use Ctrl+K+D together for same objective.

Formatted alignment Code Snippet:

private void btnSubmit_Click(object sender, EventArgs e)
        {
            if (txtName.Text != String.Empty)
            {
                lblClientName.Text = txtName.Text;
            }
            else
            {
                lblError.Text = "Blank fields not allowed.";
            }
        }

Points of Interest:

  • If there are syntax error in structure of  code such as missing closing braces then this will not work.
  • To format only specific portion of code, select that code, and use Ctrl-K, Ctrl-F one after another. Or you can use Ctrl+K+F for the same.
  • More such formatting settings can be found in Visual Studio IDE at Menu Edit > Advanced:

    Edit and Advanced

    Format Document from Edit > Advanced

Category: Tips

Leave a Reply

%d bloggers like this: