Variables
Variables represent storage locations. Every variable has a type that determines the values to be stored in the variable. C# is a type-safe language and the C# compiler guarantees that values stored in variables are always of the appropriate type. The value of a variable can be changed through assignment or through use of the ++ and - operators.
Variables are values that can change as much as needed during the execution of a program. One reason you need variables in a program is to hold the results of a calculation. Hence, variables are locations in memory in which values can be stored.
Variable Declarations
In C# all variables must be declared before they are used. In the declaration you must specify a data type and a name for the variable so that memory can be set aside for the variable. An optional initial value can be included with the declaration if you know what the value should be to start.
Syntax for variable declaration
[scope] [=initial value];
Description
The scope determines the accessibility of the variable (public, local, private) and the default is private. The data type specifies what kind of data the variable will hold. Optionally the variable can be initialised to a specific value. All variables must be initialised (given a value) before they are used in any calculation. If the variables are not initialised, the compilation of the program will fail.
Value Type Variables
Value type variables are also known as stack variables because they are stored on the stack. Value type variables can be directly declared and referenced. As the variables go out of scope, they are removed from the stack, ensuring the proper destruction of the variables. As the variables are created on the stack, they are not initialised; that is the responsibility of the program. The use of an uncapitalized variable will result in a compiler error.
Example Value variable
Int n; //uncapitalized int
Long l = 327 //initialised long
Float f = 3.13 F; //float initialised from single-precision literal
Reference Type Variables
Reference type variables are made up of two parts: the reference on the stack and the object on the heap. The creation of the object and the reference to the object is commonly known as the instantiation of the object.
Example Reference variable
To declare a reference-type variable, the syntax used are:
string strMimico;
city objToronto = null;
object objGeneric;
Example Object variable
To create an object on the heap, we go through two steps, as follows:
1. Declare the variable reference.
2. Instantiate the object on the heap by calling the new operator.
City objMimico; //declare objMimico to be a reference to a an
// object of City type
objMimico = new City(); //call the constructor of the City class to return
// a reference that is stored in the objMimico reference
The two lines can be combined into one:
City objMimico = new City();