C# Coding Standards and Naming Conventions

In this post I outline a number of coding standards and naming conventions I use. My company Magnifica is a Microsoft software development company, so I'll be concentrating on C# syntax.

The standards you should choose are down to personal preference and what you find easiest to code and read. That said if you code as part of a dev team you should use commonly defined standards to ensure the code you write is easy to maintain.

Things to do

Use PascalCasing for class and method names.

public class Customer
{
  public void CreateCustomer()
  {
    //...
  }
  public void UpdateCustomer()
  {
    //...
  }
}

Nice and easy to read and in keeping with Microsoft's .NET Framework.


Use camelCasing for method arguments and local variables

public class ClickTracker
{
  public void Track(ClickEvent clickEvent)
  {
      string url = clickEvent.Url;
      // ...
  }
}

Nice and easy to read and in keeping with Microsoft's .NET Framework.


Always vertically align your curly brackets.

// Correct
class Program
{
  static void Main(string[] args)
  {
     // ...
  }
}

Serioulsy, why wouldn't you?


Use singular names for enums.

// Correct
public enum Size
{
  Tiny,
  Small,
  Medium,
  Large,
  Massive,
  Gargantuan
}

// Exception
[Flags]
public enum Directions
{
  None = 0,
  North= 1,
  East= 2, 
  South= 3, 
  West= 4
}

In keeping with Microsoft's .NET Framework and makes code natural to read.

Exception: bit field enums.


Declare all member variables at the top of a class, with static variables at the very top.

// Correct
public class UserAccount
{
  public static string DepartmentName;
  public static decimal StartingBalance;

  public DateTime DateOpened {get; set;}
  public DateTime DateClosed {get; set;}

  // Constructor
  public UserAccount()
  {
    // ...
  }
}

This is a widely accepted convention that means others don't need to hunt for variable declarations.

Things to not do

Avoid using Abbreviations.

// Correct
CustomerLocation customerLocation;

// Avoid
CustomerLocation custLocation;

// Exceptions
CustomerId customerId;
XmlDocument xmlDocument;
FtpHelper ftpHelper;

In keeping with Microsoft's .NET Framework and prevents inconsistent abbreviations. There are some exceptions though like Id, Xml, Ftp.


Do not use underscores in identifiers.

// Correct
public DateTime clientAppointment;
public TimeSpan timeLeft;

// Avoid
public DateTime client_Appointment;
public TimeSpan time_Left;

// Exception
private DateTime _registrationDate;

In keeping with Microsoft's .NET Framework and makes code more natural to read.

You can prefix private static variables with an underscore.