Variables
Variable Names
The following are the rules when naming the variables in C#:
- A name must begin with a letter that could be followed by a sequence of letters, digits (0 - 9) or underscore.
- The first character in an identifier cannot be a digit.
- It must not contain any embedded space or symbol such as
? - + ! @ # % ^ & * ( ) [ ] { } . ; : " ' / \.
However, an underscore ( _ ) can be used.
- It should not be a C# keyword.
Examples of valid and invalid variable names are displayed as below:
- Valid:
my_Car, thisYear, and long_Name_Can_beUSE
- Invalid:
my.Car, 1newBoy, and he&HisFather
Declaring Variables
Syntax for variable definition in C# is as follows:
<data_type> <variable_list>;
Here, data_type must be a valid C# data type including char, int, float, double, or any user-defined data type, and variable_list may consist of one or more identifier names separated by commas:
|
|
int i, j, k;
char c, ch;
float f, salary;
double d;
|
|
Initializing Variables
Variables are initialized (assigned a value) with an equal sign followed by a constant expression:
variable_name = value;
Variables can be initialized in their declaration:
<data_type> <name> = value;
|
|
int d = 3, f = 5;
byte z = 22;
double pi = 3.14159;
char x = 'x';
|
|