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.

Variable Declaration with the 'var' Keyword

All of the above examples explicitly specify the type of the variable, on the left hand side prior to the name. The 'var' keyword can be used to implicitly specify the variable type, based on the value being assigned. It is left to the compiler to decide the type for the variable.

Here are the above examples declared using the 'var' keyword.

var fname = "Bob";
var verify = false;
var total = 10.2f;
var current = DateTime.Now;

It should be noted that the 'var' keyword can only be used when the variable is declared and initialised at the same time and cannot be used in every situation. A good use case is where the type of the value being assigned is not clear.