Sunday, October 5, 2008

'Beautify' C# source code in VS2005

Many times I have been asked whether it is possible to 'beautify' the C# source code in Visual Studio 2005. The answer is yes, we can.

In VS2005, the Format Document command found in the Edit -> Advanced Menu is available. The keyboard shortcut is:

Ctrl-k, Ctrl-d

(i.e. press ctrl, k and d keys simultaneously)

Before Format Document command...
public class Divider
{
public static double Divide(int divident, int divisor)
{
try{return divident / divisor;}
catch (Exception ex){
throw ex;
}
}
 
public static void Main() { try
{Divider.Divide(30, 0);}
catch (Exception ex)
{Debug.WriteLine(ex.StackTrace);
}
}
}

After Format Document command...
public class Divider
{
    public static double Divide(int divident, int divisor)
    {
        try { return divident / divisor; }
        catch (Exception ex)
        {
            throw ex;
        }
    }
 
    public static void Main()
    {
        try
        { Divider.Divide(30, 0); }
        catch (Exception ex)
        {
            Debug.WriteLine(ex.StackTrace);
        }
    }
}


Tip: Another way to achieve the same result is to first find the last closing bracket in the source and then delete it, and finally re-type it.

You can also check out the other interesting features available on the Edit -> Advanced menu:


No comments: