Coding Standards In C#

Introduction

Coding standards help improve code quality and reduce the chances of errors or bugs. Coding standards, also known as coding conventions, are guidelines and best practices developers follow while writing code to ensure that the code is consistent, readable, and maintainable. These standards cover various topics, such as naming conventions, formatting, documentation, and code structure. Coding standards provide a common approach for developers to write code, which makes it easier for other developers to understand and maintain the code. They also ensure that the code is written in a way compatible with the project's requirements and goals.

Many different coding standards exist, and they can vary depending on the programming language or platform being used. For example, Microsoft has coding standards for C#, while the Linux kernel project has coding standards for C programming. In addition, many companies or development teams may have specific coding standards to ensure consistency and quality across their codebase.

Advantages of Coding Standards

  • Improved code quality: Encouraging developers to do the right things consistently directly works to enhance software quality and maintainability.
  • Improved development speed: Developers don't always need to make decisions starting from first principles.
  • Better teamwork: They help reduce needless debates on inconsequential issues and make it easier for teammates to read and maintain each other's code.

1. PascalCasing

PascalCasing is a naming convention used in programming, where the first letter of each word in a compound word is capitalized, except for the first word. For example, "PascalCasing" is an example of PascalCasing, as the first letter of each word after the first is capitalized. This convention is commonly used in naming variables, functions, classes, and other programming constructs. PascalCasing is named after the Pascal programming language, which popularized this naming convention.

For example, "MyVariableName", "MyClassName", and "MyNamespace" are all examples of identifiers written in PascalCasing.


// Public class using PascalCasing
public class CustomerDetails {
    // Public property using PascalCasing
    public string EmployeeName { get; set; }

    // Public method using PascalCasing
    public void DisplayDetails() {
        Console.WriteLine($"Customer Name: {Name}");
        // Other details could also be displayed here
    }
}



// Public interface using PascalCasing
public interface ICalculator {
    // Method signature using PascalCasing
    int Add(int x, int y);
}


// Public enum using PascalCasing
public enum TrafficLightColor {
    Red,
    Yellow,
    Green
}


// Public namespace using PascalCasing
namespace CustomerManagement 
{
    // Code here
}

// Public Struct Using PascalCasing
public struct EmployeeData {
    public string Name;
    public int ID;
    public string Department;

    public string GetFullName() {
        return $"{this.FirstName} {this.LastName}";
    }

    // Other methods for manipulating employee data go here
}

2. camelCasing

CamelCasing is a naming convention in computer programming where multiple words are concatenated together to form a single name, and the first word is in lowercase while the first letter of each subsequent word is capitalized. The term "camelCasing" comes from the visual resemblance of the concatenated words to the humps of a camel. The first letter of the first word is lowercase, giving the appearance of a camel's head, while the capitalized letters of the subsequent words resemble the humps of a camel.

camelCasing is a naming convention used in programming languages such as C# and Java for naming identifiers such as variables, methods, and parameters. In camelCasing, the first letter of the first word is lowercase, and the first letter of each subsequent word is capitalized, without spaces between the words.

For example, "myVariableName", "myMethodName", and "myParameter" are all examples of identifiers written in camelCasing.  


// Variable name in CamelCasing
int intialValue = 10;


// Method name in  CamelCasing
public void calculateDiscount(int itemQuantity, decimal itemPrice) {
    decimal discount = 0m;
    if (itemQuantity > 10) {
        discount = 0.1m;
    }
    else if (itemQuantity > 5) {
        discount = 0.05m;
    }
    decimal total = itemQuantity * itemPrice * (1 - discount);
    Console.WriteLine($"Total price after discount: {total:C}");
}



// Field Name in CamelCasing

private string CompanyName = "Xyz Company";


// Parameter Name in  CamelCasing
public void PrintFullName(string firstName, string lastName) {
    Console.WriteLine($"{firstName} {lastName}");
}




3. Use meaningful and descriptive names for all Identifiers Name

Identifiers refer to the names of variables, functions, classes, interfaces, and other programming constructs. It is important to use meaningful and descriptive names for identifiers to improve the readability and maintainability of the code.

// Variables

int age = 25;  // A variable that stores an age value
string firstName = "John";  // A variable that stores a first name
bool isStudent = true;  // A variable that stores a boolean value indicating whether someone is a student


// Function 

int CalculateSum(int[] numbers) {
    // Code for calculating the sum of an array of numbers goes here
}

bool IsPalindrome(string text) {
    // Code for checking if a string is a palindrome goes here
}

void PrintGreeting(string name) {
    // Code for printing a personalized greeting goes here
}


// Classes

public class Customer {
    public string Name { get; set; }
    public string Email { get; set; }
    public DateTime DateOfBirth { get; set; }

    public void SendEmail(string message) {
        // Code for sending an email to the customer goes here
    }
}

public class Order {
    public int OrderNumber { get; set; }
    public Customer Customer { get; set; }
    public decimal TotalAmount { get; set; }

    public void ProcessPayment() {
        // Code for processing a payment for the order goes here
    }
}

In each of the above examples, the identifiers have been named in a meaningful and descriptive way. This makes it easier to understand what each identifier is used for and how it fits into the overall logic of the code. By using descriptive names for identifiers, the code becomes more readable and maintainable, which in turn, makes it easier to debug and modify as needed.

4. Use the var keyword for implicit typing when the type is obvious from the right side of the assignment.

In C#, the var keyword allows for implicit typing, which means that the compiler infers the type of a variable based on the right side of the assignment. The var keyword is often used when the type is obvious from the right side of the assignment.

// Without var
List<string> fruits = new List<string> { "apple", "banana", "orange" };

// With var
var fruits = new List<string> { "apple", "banana", "orange" };



// Without var
string name = "John";
int age = 30;
DateTime dateOfBirth = new DateTime(1991, 1, 1);

// With var
var name = "John";
var age = 30;
var dateOfBirth = new DateTime(1991, 1, 1);


// Declare and initialize a list of integers
var numbers = new List<int> { 1, 2, 3, 4, 5 };

// Declare and initialize a dictionary with string keys and integer values
var dictionary = new Dictionary<string, int> { { "one", 1 }, { "two", 2 }, { "three", 3 } };

// Declare and initialize a string with a hard-coded value
var message = "Hello, world!";

// Declare and initialize an integer with the result of a simple expression
var sum = 2 + 2;

// Declare and initialize an object with a null value
var obj = null;

Using var, these Above cases can make the code more concise and readable since it avoids repeating the type of information on both sides of the assignment. It can also make it easier to refactor the code in the future since the variable type can be changed without having to update the declaration.

5. Use braces for all control statements, even when the body is a single line.

Using braces for all control statements, even when the body is a single line, is a recommended best practice in many programming languages, including C#. While omitting the braces may save a few characters in code, it can make the code harder to read, especially when there are nested control statements. Also, it can make it easier to introduce bugs when modifying the code in the future. Using braces, even for single-line control statements, makes the code more consistent and easier to read. It also makes it easier to add more statements to the control structure in the future without adding the braces later.

// Example 1: if statement
if (condition) 
{
    // multiple lines of code
    Console.WriteLine("Condition is true.");
    DoSomething();
}

// Example 2: while loop
while (condition) 
{
    // single line of code
    counter++;
}

// Example 3: for loop
for (int i = 0; i < 10; i++) 
{
    // multiple lines of code
    Console.WriteLine("Iteration {0}", i);
    DoSomething();
}

// Example 4: switch statement
switch (value) 
{
    case 1:
        Console.WriteLine("Value is 1.");
        break;
    case 2:
        Console.WriteLine("Value is 2.");
        break;
    default:
        Console.WriteLine("Value is neither 1 nor 2.");
        break;
}

Braces are used for all control statements in each of these examples, even when the body is a single line. This can help make the code more consistent and easier to read, especially when working with larger codebases or collaborating with other developers.

6. Use four spaces for indentation

Indentation makes the code more readable and easier to understand, especially when there are nested control structures or long blocks of code. Using four spaces for indentation makes the code more consistent and easier to read, even if different developers use different editors or settings. Using four spaces for indentation is a recommended best practice in many programming languages, including C#.

public void MyMethod()
{
    if (condition)
    {
        for (int i = 0; i < 10; i++)
        {
            Console.WriteLine("Loop iteration: " + i);
        }
    }
    else
    {
        while (otherCondition)
        {
            Console.WriteLine("Still in the loop...");
        }
    }
}

In this example, four spaces are used for each indentation level, making the code easier to read and understand. Consistent indentation also helps make the code structure more visible, allowing developers to identify nested control structures or blocks of code quickly.

7. Use a single space after a comma and a semicolon, and no spaces before them

Using a single space after a comma and a semicolon, and no spaces before them, is a common coding convention that improves the readability and consistency of code. 

// Comma with space after
string[] fruits = { "apple", "banana", "orange" };

// Semicolon with space after
int a = 10;
int b = 20;

// No space before comma
string fullName = "John,Doe";

// No space before semicolon
if (condition) {
    // code goes here
} else {
    // code goes here
}

In these examples, a single space is used after the comma and semicolon, but there are no spaces before them. This helps to make the code more consistent and easier to read since the spacing is uniform throughout the code.

8. Use parentheses for clarity, even when they are optional

Using parentheses for clarity, even when they are optional, is a coding convention that can make the code more readable and easier to understand, especially for developers unfamiliar with the codebase. 

// Optional parentheses omitted
if (condition)
    statement;

// Optional parentheses included
if (condition) {
    statement;
}

// Optional parentheses omitted
while (condition)
    statement;

// Optional parentheses included
while (condition) {
    statement;
}

// Optional parentheses omitted
for (int i = 0; i < count; i++)
    statement;

// Optional parentheses included
for (int i = 0; i < count; i++) {
    statement;
}

// Optional parentheses omitted
return value;

// Optional parentheses included
return (value);

In these examples, optional parentheses are included even when not required. This helps to make the code more consistent and easier to read since the parentheses are used consistently throughout the code. This can be especially helpful when reading complex or nested statements, where using parentheses can make the code more readable and easier to understand.

9. Avoid using abbreviations or acronyms unless they are well-known and commonly used

Using abbreviations or acronyms in code can make it more difficult to read and understand, especially for developers unfamiliar with the codebase or the specific domain. It is generally recommended to avoid using abbreviations or acronyms unless they are well-known and commonly used in the domain or industry.

// Bad example using abbreviation
int numRecs = GetNumberOfRecords();

// Good example using full name
int numberOfRecords = GetNumberOfRecords();

// Bad example using acronym
public void CreateGUI() {
    // code goes here
}

// Good example using full name
public void CreateGraphicalUserInterface() {
    // code goes here
}

In the above example, an abbreviation or acronym is used to represent a concept or term, which can make the code more difficult to understand in case of a Bad example when the full name is used to represent the same concept or term, which makes the code more clear and easier to understand. By avoiding abbreviations and acronyms in code, developers can make their code more accessible and easier to understand for everyone.

10. Avoid using underscores in identifier names, except for fields

Using underscores in identifier names can make the code less readable and harder to understand, especially for non-native speakers. In general, it's recommended to use camelCasing for identifier names instead of underscores.

// Avoid
string first_name = "John";
int max_value = 100;

// Prefer
string firstName = "John";
int maxValue = 100;


// Avoid
public class my_class {
    // code goes here
}

// Prefer
public class MyClass {
    // code goes here
}



// Avoid
enum day_of_week {
    Monday,
    Tuesday,
    Wednesday,
    Thursday,
    Friday,
    Saturday,
    Sunday
}

// Prefer
enum DayOfWeek {
    Monday,
    Tuesday,
    Wednesday,
    Thursday,
    Friday,
    Saturday,
    Sunday
}

Summary 

By following these coding standards, you can improve your C # code's readability, maintainability, and performance of your C# code and make it easier to work with for yourself and other developers.

Thank you for reading, and I hope this blog post has helped provide you with a better understanding of the Coding standards in C#.


Similar Articles