Variables are containers for storing data values. Its value can be changed and used many times in the program.
The variable has type, name and value. When creating a variable, a place in memory is allocated for it where the value itself will be stored.
The syntax for declaring a variable:
type variable_name;
First we declare the type of the variable then the name, which must match the following conditions:
- variable name should not contain punctuation marks and spaces;
- variable name cannot be a C# keyword. We talked about it in C# keywords.
- variable name can have alphabets, digits and underscore.
- variable name can starts with underscore and alphabet symbols, but not with digits.
Example:
After defining the variable, you can assign some value:
❗Tip: variable names should correspond as closely as possible to what the variable stores.
It is important to remember that you can assign a value to variable that correspond to the variable type. If we declared a string, then we cannot a store number to it:
Let’s see how you can access variables:
Result:
Constants
The value of variables can be changed in any part of the program. But what if we want to declare a variable whose value will be immutable? Here we can use constants. The constant must be initialized when defining and once defined, the constant cannot be changed.
To declare a variable as a constant, you need to write the const keyword before the variable type:
Basically, constants are declared in uppercase, but this is nothing more than convention.
Previous article -> 2.1 Program structure
Next article -> 2.3 Data Types
Join to our community in Telegram — https://t.me/itifico
If you want to support me, you can buy me a cup of coffee and I will drink it when I write the next article :)
Donations list:
- Dinesh Chintalapudi — 3$
- Unknown — 5$
- Neisy — 3$