C# Variables

A variable is nothing more than a name given to a particular area in memory that stores a value created by a C# script. Each variable is assigned a specific type, which limits what values can be stored in it, for example, an integer, a decimal or floating-point number, or a string. Once created the value of a variable can be changed. A variable can be declared simply by specifying its type and the name.

int x;

In the above example, an integer variable has been declared with the name ‘x’. A value can then be assigned to the variable as follows.

x = 10;

Here the number 10 has been assigned to the variable ‘x’. The declaration of a variable and the assignment of its initial value can actually be done together, so the above could be re-written like this.

int x = 10;

Multiple variables of the same type can also be declared together in a single line of code.

int x, y, z;

Here three integer variables, x, y and z, have been declared together. Multiple variables can also be declared and initialised in one line of code.

int x = 10, y = 20, z = 30;

Here are some other examples of variable declarations.

// An initialised string variable.
string fname = "Bob";

/* A boolean variable initialised to false.
   A boolean variable can either be true or false. */
bool verify = false;

/* An initialised float variable.
   A float variable can hold a number with decimal places.
   Note the 'f' after the number, which ensures it is treated as a float. */
float total = 10.2f;

/* An initialised datetime variable, set to the current date and time.
   The format may vary depending on the Operating System regional settings. */
DateTime current = DateTime.Now;

The examples shown here are just a small number of the types of variables that are available.