How to: Reformat your code in Visual Studio
We're all really fast at coding, right. So you don't want to bother with things like proper casing of keywords (in VB.Net) and properly re-aligning the code. Well, Visual Studio can do that for you with just a few keystrokes. I noticed that not that many people are aware of this option, but I actually use it quite often. Especially when looking at existing code, I use this key-combination to make sure the code is properly aligned. So let me explain how this key-combination works and what it can and cannot do.
Reformat VB.Net code
Suppose I have the VB.Net as it is shown here:
private _myPropertyValue as String
public property PropertyValue as string
get
return _myPropertyValue
End Get
set
_myPropertyValue = value
End Set
End Property
This code will compile and it will work. However, you will also notice that the casing of keywords is not as you would expect as a VB.Net developer. To re-format the code, follow these three steps:
- Select the code you want to re-format.
- Press Ctrl-K
- Press Ctrl-F
The code should now look like this:
Private _myPropertyValue As String
Public Property PropertyValue() As String
Get
Return _myPropertyValue
End Get
Set(ByVal Value As String)
_myPropertyValue = Value
End Set
End Property
As you will see, all VB.Net keywords are now properly cased. But you also get the (ByVal Value As String) code after the Set keyword, all for free. The key combination Ctrl-K + Ctrl-F only works on selected text, so make sure you select the code you want to re-format before using it. You can easily reformat the entire code by pressing Ctrl-A + Ctrl-K + Ctrl-F.
Reformat C# code
The key combination also works in C#. But the functionality in C# is really only useful to re-align the code. Look at the following example:
internal class temp { private string _mypropertyvalue;
public string PropertyValue { get { return _mypropertyvalue;
}
set { _mypropertyvalue = value;
}
}
}
When you use the Ctrl-K + Ctrl-F combination to reformat the code, it will look like this:
internal class temp
{ private string _mypropertyvalue;
public string PropertyValue
{ get
{ return _mypropertyvalue;
}
set
{ _mypropertyvalue = value;
}
}
}
As you will undoubtedly notice, the code is merely re-aligned. But I still found it useful in C#, because I don't have to worry about re-aligning my code. I just use this key-combination to do it for me.