C sharp - Rules for Identifiers in C#

In C#, identifiers are the names used for variables, methods, classes, namespaces, and other user-defined elements. They must follow specific rules and conventions to be valid.

1. Must Begin with a Letter or Underscore

  • The first character of an identifier must be a letter (A–Z, a–z) or an underscore (_).

  • It cannot begin with a digit.

 Valid: name, _value, user1
  Invalid: 1user, @value#

2. Can Contain Letters, Digits, and Underscores

  • After the first character, identifiers can include:

    • Letters (A–Z, a–z)

    • Digits (0–9)

    • Underscores (_)

 Valid: score_2025, dataSet1
 Invalid: data-set, user@name

3. Cannot Be a C# Keyword (Unless Escaped)

  • You cannot use C# reserved keywords (e.g., class, int, for) as identifiers unless you prefix them with @.

 Valid: @class, @int
 Invalid: class, int (as unescaped identifiers)

4. Case-Sensitive

  • C# identifiers are case-sensitive.
    Value and value are two different identifiers.

 Valid: Count, count, COUNT (all distinct)

5. No Special Characters or Spaces

  • You cannot include symbols like !, #, @, -, spaces, or other special characters (except underscore).

❌ Invalid: user-name, first name, total$

6. Must Not Conflict with .NET Framework Names

  •  

    While technically allowed, avoid naming identifiers that conflict with existing .NET types, like string, Console, or Task.

Examples of Valid Identifiers

int _score;
double price2025;
string userName;
bool isLoggedIn;

Examples of Invalid Identifiers

int 2value;     // Starts with digit
float user-name; // Hyphen not allowed
string for;     // 'for' is a keyword
char full name; // Space not allowed