Wednesday 16 July 2014

C# Coding Standards and Naming Conventions

Below are our C# coding standards, naming conventions, and best practices. Use these in your own projects and/or adjust these to your own needs.

1. Naming Conventions and Style 
douse PascalCasing for class names and method names.
public class ClientActivity
{
    public void ClearStatistics()
    {
        //...
    }
    public void CalculateStatistics()
    {
        //...
    }
}
Why: consistent with the Microsoft's .NET Framework and easy to read.
douse camelCasing for method arguments and local variables.
public class UserLog
{
    public void Add(LogEvent logEvent)
    {
        int itemCount = logEvent.Items.Count;
        // ...
    }
}
Why: consistent with the Microsoft's .NET Framework and easy to read.
do notuse Hungarian notation or any other type identification in identifiers
// Correct
int counter;
string name;
 
// Avoid
int iCounter;
string strName;
Why: consistent with the Microsoft's .NET Framework and Visual Studio IDE makes determining types very easy (via tooltips). In general you want to avoid type indicators in any identifier.
do notuse Screaming Caps for constants or readonly variables
// Correct
public static const string ShippingType = "DropShip";
 
// Avoid
public static const string SHIPPINGTYPE = "DropShip";
Why: consistent with the Microsoft's .NET Framework. Caps grap too much attention.
avoidusing Abbreviations. Exceptions: abbreviations commonly used as names, 
                 such as Id, Xml, Ftp, Uri
// Correct
UserGroup userGroup;
Assignment employeeAssignment;
 
// Avoid
UserGroup usrGrp;
Assignment empAssignment;
 
// Exceptions
CustomerId customerId;
XmlDocument xmlDocument;
FtpHelper ftpHelper;
UriPart uriPart;
Why: consistent with the Microsoft's .NET Framework and prevents inconsistent abbreviations.
douse PascalCasing for abbreviations 3 characters or more (2 chars are both uppercase)
HtmlHelper htmlHelper;
FtpTransfer ftpTranfer;
UIControl uiControl;
Why: consistent with the Microsoft's .NET Framework. Caps would grap visually too much attention.
do notuse Underscores in identifiers. Exception: you can prefix private static variables 
                    with an underscore.
// Correct
public DateTime clientAppointment;
public TimeSpan timeLeft;
 
// Avoid
public DateTime client_Appointment;
public TimeSpan time_Left;
 
// Exception
private DateTime _registrationDate;
Why: consistent with the Microsoft's .NET Framework and makes code more natural to read (without 'slur'). Also avoids underline stress (inability to see underline).
douse predefined type names instead of system type names like Int16, Single, UInt64, etc
         
// Correct
string firstName;
int lastIndex;
bool isSaved;
 
// Avoid
String firstName;
Int32 lastIndex;
Boolean isSaved;
Why: consistent with the Microsoft's .NET Framework and makes code more natural to read. 
douse implicit type var for local variable declarations. Exception: primitive types (int, string, 
          double, etc) use predefined names.
var stream = File.Create(path);
var customers = new Dictionary<int?, Customer>();
 
// Exceptions
int index = 100;
string timeSheet;
bool isCompleted;
Why: removes clutter, particularly with complex generic types. Type is easily detected with Visual Studio tooltips.
douse noun or noun phrases to name a class.
public class Employee
{
}
public class BusinessLocation
{
}
public class DocumentCollection
{
}
Why: consistent with the Microsoft's .NET Framework and easy to remember.
doprefix interfaces with the letter I.  Interface names are noun (phrases) or adjectives.
public interface IShape
{
}
public interface IShapeCollection
{
}
public interface IGroupable
{
}
Why: consistent with the Microsoft's .NET Framework.
doname source files according to their main classes. Exception: file names with partial classes
          reflect their source or purpose, e.g. designer, generated, etc.
// Located in Task.cs
public partial class Task
{
    //...
}
// Located in Task.generated.cs
public partial class Task
{
    //...
}
Why: consistent with the Microsoft practices. Files are alphabetically sorted and partial classes remain adjacent.
doorganize namespaces with a clearly defined structure
// Examples
namespace Company.Product.Module.SubModule
namespace Product.Module.Component
namespace Product.Layer.Module.Group
Why: consistent with the Microsoft's .NET Framework. Maintains good organization of your code base.
dovertically align curly brackets.
// Correct
class Program
{
    static void Main(string[] args)
    {
    }
}
Why: Microsoft has a different standard, but developers have overwhelmingly preferred vertically aligned brackets.
dodeclare all member variables at the top of a class, with static variables at the very top.
// Correct
public class Account
{
    public static string BankName;
    public static decimal Reserves;
 
    public string Number {get; set;}
    public DateTime DateOpened {get; set;}
    public DateTime DateClosed {get; set;}
    public decimal Balance {get; set;}
 
    // Constructor
    public Account()
    {
        // ...
    }
}
Why: generally accepted practice that prevents the need to hunt for variable declarations.
douse singular names for enums. Exception: bit field enums.
// Correct
public enum Color
{
    Red,
    Green,
    Blue,
    Yellow,
    Magenta,
    Cyan
}
 
// Exception
[Flags]
public enum Dockings
{
    None = 0,
    Top = 1, 
    Right = 2, 
    Bottom = 4,
    Left = 8
}
Why: consistent with the Microsoft's .NET Framework and makes the code more natural to read. Plural flags because enum can hold multiple values (using bitwise 'OR').
do notexplicitly specify a type of an enum or values of enums (except bit fields)
// Don't
public enum Direction : long
{
    North = 1,
    East = 2,
    South = 3,
    West = 4
}
 
// Correct
public enum Direction
{
    North,
    East,
    South,
    West
}
Why: can create confusion when relying on actual types and values.
do notsuffix enum names with Enum
// Don't
public enum CoinEnum
{
    Penny,
    Nickel,
    Dime,
    Quarter,
    Dollar
}
 
// Correct
public enum Coin
{
    Penny,
    Nickel,
    Dime,
    Quarter,
    Dollar
}
Why: consistent with the Microsoft's .NET Framework and consistent with prior rule of no type indicators in identifiers.

Visual Studio shortcut keys

You are familiar with many of Visual Studio's shortcut keys, but not all of them. Here is a handy reference that can make your .NET lifestyle easier and a lot more productive. The 'must-know' shortcut keys are highlighted.

General

ShortcutDescription
Ctrl-X or
Shift-Delete
Cuts the currently selected item to the clipboard
Ctrl-C or
Ctrl-Insert
Copies the currently selected item to the clipboard
Ctrl-V or
Shift-Insert
Pastes the item in the clipboard at the cursor
Ctrl-Z or
Alt-Backspace
Undo previous editing action
Ctrl-Y or
Ctrl-Shift-Z
Redo the previous undo action
Ctrl-Shift-V or
Ctrl-Shift-Insert
Pastes an item from the clipboard ring tab of the Toolbox at the cursor in the file and automatically selects the pasted item. Cycle through the items on the clipboard by pressing the shortcut keys repeatedly
Esc Closes a menu or dialog, cancels an operation in progress, or places focus in the current document window
Ctrl-S Saves the selected files in the current project (usually the file that is being edited)
Ctrl-Shift-S Saves all documents and projects
Ctrl-PDisplays the Print dialog
F7Switches from the design view to the code view in the editor
Shift-F7Switches from the code view to the design view in the editor
F8Moves the cursor to the next item, for example in the TaskList window or Find Results window
Shift-F8Moves the cursor to the previous item, for example in the TaskList window or Find Results window
Shift-F12 Finds a reference to the selected item or the item under the cursor
Ctrl-Shift-GOpens the file whose name is under the cursor or is currently selected
Ctrl-/Switches focus to the Find/Command box on the Standard toolbar
Ctrl-Shift-F12Moves to the next task in the TaskList window
Ctrl-Shift-8Moves backward in the browse history. Available in the object browser or Class View window
Alt-Left ArrowGo back in the web browser history
Alt-Right ArrowGo forward in the web browser history

Text navigation

ShortcutDescription
Left Arrow Moves the cursor one character to the left
Right Arrow Moves the cursor one character to the right
Down Arrow Moves the cursor down one line
Up Arrow Moves the cursor up one line
Page Down Scrolls down one screen in the editor window
Page Up Scrolls up one screen in the editor window
End Moves the cursor to the end of the current line
HomeMoves the cursor to the beginning of the line. If you press Home when the cursor is already at the start of the line, it will toggle the cursor between the first non-whitespace character and the real start of the line
Ctrl-End Moves the cursor to the end of the document
Ctrl-Home Moves the cursor to the start of the document
Ctrl-GDisplays the Go to Line dialog. If the debugger is running, the dialog also lets you specify addresses or function names to go to
Ctrl-] Moves the cursor to the matching brace in the document. If the cursor is on an opening brace, this will move to the corresponding closing brace and vice versa
Ctrl-K, Ctrl-NMoves to the next bookmark in the document
Ctrl-K, Ctrl-PMoves to the previous bookmark
Ctrl-K, Ctrl-IDisplays Quick Info, based on the current language
Ctrl-Down Arrow Scrolls text down one line but does not move the cursor. This is useful for scrolling more text into view without losing your place. Available only in text editors
Ctrl-Up Arrow Scrolls text up one line but does not move the cursor. Available only in text editors
Ctrl-Right Arrow Moves the cursor one word to the right
Ctrl-Left Arrow Moves the cursor one word to the left
Ctrl-Shift-1Navigates to the next definition, declaration, or reference of an item. Available in the object browser and Class View window. Also available in source editing windows if you have already used the Edit.GoToReference (Shift-F12) shortcut
Ctrl-Shift-2Navigates to the previous definition, declaration, or reference of an item


Text manipulation

ShortcutDescription
Enter Inserts a new line
DeleteDeletes one character to the right of the cursor
InsertToggles between insert and overtype insertion modes
TabIndents the currently selected line or lines by one tab stop. If there is no selection, this inserts a tab stop
Shift-Tab Moves current line or selected lines one tab stop to the left
Backspace or
Shift-Backspace
Deletes one character to the left of the cursor
Ctrl-K, Ctrl-CMarks the current line or selected lines of code as a comment, using the correct comment syntax for the programming language
Ctrl-K, Ctrl-URemoves the comment syntax from the current line or currently selected lines of code
Ctrl-T or
Shift-Enter
Swaps the characters on either side of the cursor. (For example, AC|BD becomes AB|CD.) Available only in text editors
Ctrl-K, Ctrl-LRemoves all unnamed bookmarks in the current document
Ctrl-M, Ctrl-OAutomatically determines logical boundaries for creating regions in code, such as procedures, and then hides them. This collapses all such regions in the current document
Alt-Right Arrow or
Ctrl-Spacebar
Displays statement completion based on the current language or autocompletes word if existing text unambiguously identifies a single symbol
Ctrl-K, Ctrl-\ Removes horizontal whitespace in the selection or deletes whitespace adjacent to the cursor if there is no selection
Ctrl-K, Ctrl-FApplies the indenting and space formatting for the language as specified on the Formatting pane of the language in the Text Editor section of the Options dialog to the selected text.
Ctrl-LCuts all selected lines or the current line if nothing has been selected to the clipboard
Ctrl-Shift-LDeletes all selected lines or the current line if no selection has been made
Ctrl-Enter Inserts a blank line above the cursor
Ctrl-Shift-Enter Inserts a blank line below the cursor
Shift-Alt-T Moves the line containing the cursor below the next line
Ctrl-JLists members for statement completion when editing code
Ctrl-UChanges the selected text to lowercase characters
Ctrl-Shift-UChanges the selected text to uppercase characters
Ctrl-Shift-Spacebar Displays a tooltip that contains information for the current parameter, based on the current language
Ctrl-M, Ctrl-URemoves the outlining information for the currently selected region
Ctrl-M, Ctrl-PRemoves all outlining information from the entire document
Ctrl-R, Ctrl-PSwaps the anchor and endpoint of the current selection
Ctrl-M, Ctrl-LToggles all previously marked hidden text sections between hidden and display states
Ctrl-K, Ctrl-KSets or removes a bookmark at the current line
Ctrl-M, Ctrl-MToggles the currently selected hidden text section or the section containing the cursor if there is no selection between the hidden and display states
Ctrl-K, Ctrl-HSets or removes a shortcut in the tasklist to the current line
Ctrl-R, Ctrl-REnables or disables word wrap in an editor
Ctrl-R, Ctrl-WShows or hides spaces and tab marks
Ctrl-Delete Deletes the word to the right of the cursor
Ctrl-Backspace Deletes the word to the left of the cursor
Ctrl-Shift-TTransposes the two words that follow the cursor. (For example, |End Sub would be changed to read Sub End|.)
Ctrl-.[dot]Display options on smarttag menu.
Very useful for showing using/Imports options.