The next topic in our lessons will be declaring and initializing variables. What do those terms 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, or, more correctly, it contains the default value of its type. This is where initialization comes in.
Initializing a variable means declaring a variable and assigning 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
10
11
12
13
14
15
16
17
18
19
20
21
22
|
using
System;
namespace
HelloWorld
{
class
Program
{
static void Main(string[] args)
{
// 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;
Console.ReadLine();
}
}
}
|
It is also possible to merge the two terms in a single instruction:
|
17
|
int height = 158;
|
The compiler also allows us to declare multiple variables of the same type in a single instruction:
|
9
|
int height, weight, age;
|
As you could guess, the compiler also allows us to initialize variables declared in a single instruction, but this is a not so popular feature among programmers:
|
9
|
int height = 169, weight, age = 24;
|
The concepts explained in this lesson are also shown visually as part of the following video: