Skip to main content

Variables

Variables are used to store data in a program. A variable is a named memory area in which a value of a certain type is stored. A variable has a type, a name, and a value. The type determines what kind of information the variable can store.

Any variable must be defined before it can be used. The syntax for defining a variable is as follows:

type variable_name;

First comes the type of the variable, then its name. The variable name can be any arbitrary name that satisfies the following requirements:

  • the name may contain any digits, letters and underscore character, and the first character in the name must be a letter or underscore character

  • the name must not contain punctuation and spaces

  • the name cannot be a C# keyword. There are not many such words, and when working in Visual Studio, the development environment highlights keywords in blue.

Although the name of a variable can be anything, you should give variables descriptive names that will tell about their purpose.

For example, let's define the simplest variable:

string name;

In this case, the variable name is defined, which is of type string. that is, the variable represents a string. Since the variable definition is an instruction, it is followed by a semicolon.

Note that C# is a case-sensitive language, so the next two variable definitions will represent two different variables:

string name;
string Name;

Once a variable has been defined, you can assign some value to it:

string name;
name = "BTC";

Since the variable name represents the string type, i.e. a string, we can assign it a string in double quotes. And the variable can be assigned only the value that corresponds to its type.

In the future we can use the variable name to access the memory area where its value is stored.

We can also assign a value to a variable right after defining it. This technique is called initialization:

string name = "BTC";

A distinctive feature of variables is that you can change their value repeatedly in a program. For example, let's create a small program in which we define a variable, change its value and display it on the console:

string name = "BTC";  // define a variable and initialize it

// BTC

name = "ETH"; // change the value of the variable

// ETH