In C#, identifiers are the user-defined names given to program elements such as variables, methods, classes, and labels. They are used to identify these elements in a program. Example:
// Declaring a variable
int x = 10;
// Defining a class
class GFG { }
// Defining a method
void Main() { }
In the above code block- "x", "GFG" and "Main" are identifiers representing a variable, class, and method, respectively and are user-defined names used to uniquely identify program elements in C#.
Rules for Defining Identifiers
There are certain valid rules for defining a valid C# identifier. These rules should be followed, otherwise, we will get a compile-time error.
Aspect | Description |
|---|---|
Allowed Characters | The only allowed characters for identifiers are all alphanumeric characters([A-Z], [a-z], [0-9]), '_' (underscore). |
Starting Character | Identifiers should not start with digits([0-9]). For example, "123geeks" is not valid in the C# identifier. |
No Whitespaces | Identifiers must not contain whitespace characters. |
Keywords | Identifiers are not allowed to use as keywords unless they include @ as a prefix. For example, @as is a valid identifier, but "as" is not because it is a keyword. |
Unicode Support | C# identifiers allow Unicode Characters. |
Case - Sensitivity | C# identifiers are case-sensitive. |
Length Restriction | There is no strict length limit defined for identifiers in C#, but they should be kept short and meaningful for readability. |
Underscore Usage | Identifiers can contain underscores, but using consecutive underscores (e.g., __name) is discouraged as such patterns are typically reserved for internal or compiler-generated use. |
Types of Identifiers
Identifiers in C# can represent different program elements:
- Class Identifiers: Names of classes (e.g., GFG)
- Method Identifiers: Names of methods (e.g., Main)
- Variable Identifiers: Names of variables (e.g., x)
- Object Identifiers: Names of objects created from classes
using System;
class Geeks
{
static public void Main()
{
int a = 10;
int b = 39;
int c;
c = a + b;
Console.WriteLine("The sum of two numbers is: {0}", c);
}
}
Output
The sum of two numbers is: 49
In the above example:
- Keywords: using, public, static, void, int.
- Identifiers: Geeks, Main , a, b, c.
Naming Conventions for Identifiers
Use meaningful names (e.g., totalMarks instead of tm). Use the following naming conventions:
- PascalCase: for classes and methods (StudentData)
- camelCase: for variables (studentAge)
Avoid using reserved keywords as identifiers.