Naming conventions in C#
A set of guidelines and suggestions for naming different programming components, including variables, classes, methods, properties, interfaces, enumerations, and namespaces, are known as C# naming conventions. Although the compiler doesn’t enforce these rules, they are essential for producing code that is legible, maintainable, and of high quality especially in big projects with several developers. Program readability can be significantly decreased by inconsistent naming convention use, which can also make future modifications more challenging.
General Principles of Naming Conventions
Meaningful and Descriptive Names: Identifiers ought to specify their function or role in the code in detail. Stay away from names that are too short or unclear, such as Problem12, A37, or K.
Consistency: Every member of the development team should use the same naming conventions throughout the project. Utilize the same terms for comparable circumstances and symmetrically name opposing functions (e.g., LoadLibrary() and UnloadLibrary()).
Use English: When naming comments or identifiers, always use English. In software development, this is a de facto standard.
Avoid Abbreviations (Generally): It’s usually advisable to stay away from acronyms unless they are well-known (e.g., HTML, URL) because they can be confusing.
Case Sensitivity: Due of C#’s case sensitivity, class differs from class and age differs from age.
Casing Conventions
The two main case styles used in C# name conventions are:
Pascal Case: Each concatenated word’s first letter and the first letter in the identifier are capitalised.
- Examples: BackColor, ValueChanged, and AppDomain.
Camel Case: Every following concatenated word’s first letter is capitalised, but the initial letter of an identifier is lowercase.
- Examples: BackColor, carName, and typeName.
Specific Naming Rules and Recommendations with Examples
Identifiers (General)
A class, variable, function, or other user-defined object is called an identifier.
Allowed Characters: It can include the underscore symbol (_), numeric digits (0–9), and letters (uppercase and lowercase).
Starting Character: It can begin with an underscore or a letter, but it shouldn’t begin with a number.
Special Symbols: Except for the underscore symbol, which is typically avoided in variable names for better programming style, there shouldn’t be any special symbols or whitespace present.
Uniqueness: Within its scope, an identifier needs to be unique.
Keywords: Unless the @ character is prefixed, keywords cannot be used as identifiers (char is not valid, but @char is).
Length: An identifier can have any length, but the compiler only takes into account the first 31 characters.
Example (Valid): Marks, studentName, _name1.
The example is invalid: 1
(digit), if
(keyword), 1name
(starts with digit), a b
(whitespace), str-
(special symbol).
Variables
Each variable in C# needs to be declared with a specific data type and name before it can be used. Variables are memory locations for storing data.
Casing: When dealing with member variables (fields in a class) and local variables, use camel casing.
Recommendations:
- Descriptive: The data that they contain should be carefully and clearly described by their names.
- Single Purpose: To prevent confusion and to make it easier to select a suitable name, use a single variable for a single purpose.
- Underscores: Since it could clash with system names, avoid beginning with an underscore (_). Additionally, refrain from dividing words (such as first_name) with underscores.
- Length: While 10 to 16 characters is the ideal length, intelligibility comes first. More detailed labels are needed for variables having a broader scope.
Boolean Variables: Names ought to convey truth or falsity. Prefixes like is, has, or can are frequently used (e.g., canRead, available, isOpen, valid, hasPendingPayment, isPrime). Steer clear of negated names, like!notFound.
Classes
The behaviour of objects is defined by their classes.
Casing: Make use of Pascal casing.
Names: Must include a noun or a noun phrase.
Examples: AppDomain
, Dog
, Account
, Car
, PrimeNumbersFinder
.
Bad Examples: FindPrimeNumber
(verb), Numbers
(unclear).
Source File: Typically, a distinct.cs file with a name that matches the class name is used to define each class. Unlike Java, C# permits more than one public class declaration in a single source file.
Methods
Code segments that carry out particular operations are called methods.
Casing: Make use of Pascal casing.
Names: Usually includes a verb or a verb and a noun or object, and should describe an activity.
Purpose: Every technique should accomplish a unique, clearly defined task (strong coherence).
Methods Returning Values: The returned value should be described by the names (e.g., GetNumberOfProcessors(), FindMinPath(), CreateNewInstance()).
Parameters: Put parameter names in camel casing. Within the method body, parameters shouldn’t be utilised as local variables; instead, they should have meaning. Prioritise primary parameters over the others.
Examples: PrintReport()
, LoadSettings()
, SetUserName()
. FindSmallestElement()
, Sort(int[] arr)
, ReadInputData()
.
Bad Examples: Abc11
, Yellow___Black
, foo
, _Bar
, ShowReport()
(unclear return), Value()
(should be GetValue()
or HasValue()
).
Properties
Properties are used to access underlying fields and specify a class’s attributes.
Casing: Make use of Pascal casing.
Names: Should either be a noun alone, without a verb, or an adjective plus a noun.
Avoid Conflicts: It might be perplexing to create a method like GetX() for a property with the name X.
Example: Name
, Color
, MyValue
, X
.
Interfaces
Interfaces establish a behaviour contract.
Casing: Make use of Pascal casing.
Prefix: To identify that the type is an interface, it should be preceded by the letter I.
Names: They may be adjectives that describe behaviour, noun phrases, or nouns.
Examples: IServiceProvider
, IComponent
, IDisposable
, IEnumerable
.
Enumerations (Enums)
Value types known as enumerations are capable of accepting a number of predetermined, constant values.
Casing: For the enumeration type and its members, use Pascal casing.
Names: For the majority of enums (like Volume), use a singular name; however, for bit fields and enum types that have the [Flags] attribute, use a plural name (like MyColors).
Avoid Suffixes: Avoid using enum as a suffix (for example, VolumeEnum is not correct).
Avoid Redundant Entry Names: Don’t use the enum name in every item (for example, ColorBlue should be Blue).
Default Values: Enum members are of type int by default, with a value of zero and an increase of one. It is possible to assign explicit values.
Namespaces
Particularly when a codebase has several libraries, namespaces are utilised to classify code logically and avoid name clashes.
Casing: Dot notation (.) and Pascal casing are used for nested namespaces.
Format: The general format is <Company>.(<Product>|<Technology>)[.<Feature>][.<Subnamespace>]
(e.g., Fabrikam.Math
, Telerik.WinControls.GridView
).
Purpose: Code organization is aided by namespaces, which are virtual places as opposed to actual files. They are nested.
using
Keyword: The using
keyword is used to include namespaces, allowing classes within them to be used without their fully qualified names (e.g., using System;
allows Console.WriteLine()
instead of System.Console.WriteLine()
). Aliases can also be created for namespaces.
Constants
Immutable values or fields that are set at compile or runtime are known as constants.
Casing: For readonly and const identifiers, Microsoft suggests Pascal casing, while some developers also use ALL_CAPS (much like C++ and Java).
Purpose: Avoid “magic numbers” and “magic strings,” enhance readability, and make maintenance easier by enabling simple adjustments in one location.
When to Use: For buffer sizes, filenames, mathematical expressions, or any other variable that is frequently utilised or is subject to change over time.
When Not to Use: If internationalization is intended, use resource files for error messages, SQL queries, and UI component labels.
Tools and Refactoring for Naming
Visual Studio’s Rename Feature: Programmers can simply rename identifiers (fields, local variables, methods, namespaces, properties, and types) throughout the code using refactoring operations like “Rename,” which are provided by Integrated Development Environments (IDEs) like Visual Studio. This automatically updates all references, including those in comments and strings.
nameof
Operator (C# 6.0+): An unqualified name of a variable, type, or member is returned as a string literal by this operator. Code becomes more resilient and refactoring-friendly when it is examined at compile time and immediately updated if the referenced identifier is renamed using an IDE’s refactoring tools.
XML Documentation Comments: Code that self-documents must have proper nomenclature. Tools that process XML documentation comments (beginning with ///) in C# can produce thorough API documentation (such as MSDN-style websites). The proper naming of parameters (), return values (), and exceptions () is essential to these remarks.
You can also read Code Quality In C# Characteristics And Why It Is Important