Wednesday 4 January 2012

Variables

Variables are used to store values. More technically, a variable binds an object (in the general sense of the term, i.e. a specific value) to an identifier (the variable's name) so that the object can be accessed later. Variables can, for example, store a value for later use:
string name = "Dr. Jones";
Console.WriteLine("Good morning " + name);
In this example "name" is the identifier and "Dr. Jones" is the value that we bound to it. Also, each variable is declared with an explicit type.
Only values whose types are compatible with the variable's declared type can be bound to (stored in) the variable. In the above example we stored "Dr. Jones" into a variable of the type string. This is a legal statement. However, if we had said int name = "Dr. Jones", the compilerwould have thrown an error telling us
that you cannot implicitly convert between int and string. There are methods for doing this, but we will talk about them later.