2. What is variable?
▰ A variable is a:
❑ Placeholder of information that can usually be
changed at run-time
▰ Variables allow you to:
❑ Store information
❑ Retrieve the stored information
❑ Manipulate the stored information
2
3. IDENTIFIERS / VARIABLES
▰ Identifiers may consists of:
❑ Letters (a-z, A-Z)
❑ Digits [0-9]
❑ Underscore “_”
▰ Identifiers
❑ Can begin only with a letter or an underscore
❑ Cannot be a C# keyword
3
4. Variable (cont…)
▰ No other special characters are allowed including
space
▰ Variable names are case sensitive
❑ A and a are different.
▰ Identifiers
❑ Should have a descriptive name
❑ Should be neither too long nor too short
4
5. Declaring Variables
▰ When declaring a variable we:
❑ Specify its type
❑ Specify its name (called identifier)
❑ May give it an initial value
▰ The syntax is the following:
▰ example
5
<data_type> <identifier> [= <initialization>];
int height = 200;
6. Variable (cont…)
▰ Variables are data that will keep on changing
▰ Declaration
<<Data type>> <<variable name>>;
int a;
▰ Definition
<<varname>>=<<value>>;
a=10;
▰ Usage
<<varname>>
a=a+1; //increments the value of a by 1
6
7. Variable (cont…)
▰ Examples of correct identifiers:
▰ Examples of incorrect identifiers:
7
int New = 2; // Here N is capital
int _2Pac; // This identifiers begins with _
string nosApab = “Hello”; // Unicode symbols used
// The following is more appropriate:
string greeting = “Hello”;
int n= 100; // Undescriptive
int numberOfClients = 100; // Descriptive
// Overdescriptive identifier:
int numberOfPrivateClientOfTheFirm = 100;
int new; // new is a keyword
int 2Pac; // cannot begin with a digit
8. Declaring (cont…)
▰ Computers are machines that process data
❑ Data is stored in the computer memory in variables
❑ Variables have name, data type and value.
▰ Example of variable definition and assignment in C#
int counter = 5;
8
Variable name
Variable value
Data type
Assignment
operator
9. Declaring (cont…)
▰ Examples of variable declarations:
int myAge = 25;
▰ The equal sign (=) is an assignment operator
▰ The assignment operator works from right to left
▰ An assignment made when a variable is declared is an initialization
▰ It is not necessary to initialize a variable during a declaration.
▰ For example int myAge; is a valid declaration
9
10. Declaring (cont…)
▰ Examples of multiple variable declarations:
▻ int myAge = 25;
int yourAge = 19;
▻ int myAge = 25, your Age = 19;
▰ Declarations of variables of the same type can be separated by
commas. However, separate statements are used when declaring
variables of different types
▻ int myAge, yourAge;
double mySalary, yourSalary;
10
11. Displaying Variable Values
▰ You can display variable values by using the variable name within a
WriteLine() method call
11