The next topic in our lessons will be declaring and initializing variables. What do those term mean?
As we already said in a previous lesson, declaring a variable means creating a new variable, by telling the compiler its type and its name. However, our new variable is only created. It does not contain yet any value. This is where initialization comes in.
Initializing a variable means declaring a first, default, value to it, using the assign operator of C# (the equal character – “=”). Here is an example of declaring and initializing variables:
1 2 3 4 5 6 7 8 9 |
//declare variables int age; //the age of the user, in years int weight; //the weight of the user, in Kg int height; //the height of the user, in cm //initialize variables age = 32; weight = 48; height = 158; |
It is also possible to merge the two terms in a single instruction:
1 |
int height = 158; |
The compiler also allows us to declare multiple variables of the same type in a single instruction:
1 |
int height, weight, age; |
As you could guess, the compiler also allows us to initialize variables declared in a single instruction:
1 |
int height = 169, weight, age = 24; |
The concepts explained in this lesson are also shown visually as part of the following video:
EXERCISES
1. Declare several variables by selecting for each one of them the most appropriate of the types sbyte, byte, short, ushort, int, uint, long and ulong, in order to assign them the following values: 52,130; -115; 4825932; 97; -10000; 20000; 224; 970,700,000; 112; -44; -1,000,000; 1990; 123456789123456789.
Solution
Look up the above variable types value ranges and select the appropriate ones for the given examples.
Comments
Tags: declaring and initializing variables, variable types, variables