C# dictionary naming conventions

In this C#.Net tutorial, we will discuss C# dictionary naming conventions in detail. These guidelines will help you to write better code, especially while working with the C#.Net dictionary.

General Naming Conventions

There are a few general naming conventions in C# that also apply to dictionaries:

  1. Pascal Case: This is the most commonly used naming convention in C#. It means that the first letter of the identifier and the first letter of each subsequent concatenated word are capitalized. For example: MyDictionary.
  2. Camel Case: The first letter of an identifier is lowercase and the first letter of each subsequent concatenated word is uppercase. For example: myDictionary. This is typically used for local variables.
  3. Avoid Abbreviations: Unless it’s a widely known abbreviation, try to avoid it. It can make your code harder to understand for others who aren’t familiar with the abbreviation.
  4. Descriptive Names: Choose names that describe the purpose of the variable or what data it’s holding.

Naming Conventions for C# Dictionaries

While the above conventions can apply to any variable, there are some additional practices when naming dictionaries:

  1. Plural Naming: If a dictionary represents a collection of objects, the name of the dictionary should be plural. For example: studentsById.
  2. KeyValue Suffix: It can be helpful to suffix the dictionary name with ‘Key’ and ‘Value’ to signify what the key and value of the dictionary represent. For example: studentIdToName where the key is studentId and the value is name.

Let’s see some examples:

Example 1:

// Good practice
Dictionary<int, string> studentIdToName = new Dictionary<int, string>();

// Bad practice
Dictionary<int, string> d = new Dictionary<int, string>();

In the first example, the dictionary’s name indicates that it maps student IDs (integers) to names (strings). In the second example, the name d doesn’t tell us anything about what the dictionary is used for.

Example 2:

// Good practice
Dictionary<string, List<int>> employeeNameToProjectIds = new Dictionary<string, List<int>>();

// Bad practice
Dictionary<string, List<int>> empProjs = new Dictionary<string, List<int>>();

n the first example, the dictionary’s name clearly indicates that it maps employee names to a list of project IDs. In the second example, empProjs doesn’t clearly define what the key and value represent.

By following these naming conventions, you can make your code much easier to read and understand. I hope you got an idea about c# dictionary naming conventions.

You may also like: