2.2 Variables

Stasoz
2 min readMar 28, 2022

--

You can check this course on my website.

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.

Contents

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:

  1. Dinesh Chintalapudi — 3$
  2. Unknown — 5$
  3. Neisy — 3$

--

--

Stasoz
Stasoz

Written by Stasoz

Full Stack Developer who is inspired by new technologies