C# Identifiers - Complete Guide
Introduction to Identifiers
Identifiers are names given to programming elements such as variables, methods, classes, and namespaces in C#. Choosing meaningful identifiers improves readability and maintainability.
C# has strict rules for naming identifiers, and following conventions (PascalCase, camelCase, etc.) ensures consistency and clarity.
Identifier Naming Rules
Identifiers must follow specific rules in C#:
Example
using System;
class Program
{
static void Main()
{
string firstName = "John";
string LastName = "Doe";
int _age = 25;
string address2 = "123 Main St";
string @class = "Math 101";
Console.WriteLine(firstName);
Console.WriteLine(LastName);
Console.WriteLine(_age);
Console.WriteLine(address2);
Console.WriteLine(@class);
// Invalid examples (not allowed in C#):
// string 2ndAddress = "456 Oak St";
// string first-name = "John";
// string first name = "John";
// string class = "Math";
}
}
public class Employee
{
private string _firstName; // Private field
public string FirstName { get; set; } // Property
public void CalculateSalary() // Method
{
int hoursWorked = 40; // Local variable
double hourlyRate = 25.50;
Console.WriteLine(hoursWorked * hourlyRate);
}
public const int MaxHours = 40; // Constant
}
Output
John Doe 25 123 Main St Math 101
Naming Conventions
Conventions improve consistency across codebases:
Example
using System;
public class EmployeeManagementSystem // Class: PascalCase
{
public const int MaximumEmployees = 100; // Constant: PascalCase
private string _employeeName; // Private field: _camelCase
public string EmployeeName { get; set; } // Property: PascalCase
public void CalculateAnnualSalary() // Method: PascalCase
{
double baseSalary = 50000; // Local variable: camelCase
double bonus = 5000;
Console.WriteLine(baseSalary + bonus);
}
public void UpdateEmployee(int employeeId, string fullName)
{
_employeeName = fullName; // Parameters: camelCase
}
}
class Program
{
static void Main()
{
EmployeeManagementSystem emp = new(); // Variable: camelCase
bool isSystemActive = true;
int currentEmployees = 5;
Console.WriteLine(isSystemActive);
Console.WriteLine(currentEmployees);
}
}
Output
True 5