A C# variable is roughly the same as the variables you remember from your ninth grade algebra class: it's a placeholder for a value. To put it more technically, a variable is an instance of an intrinsic type (such as
int) that can hold a value:
int myVariable = 15;
You initialize a variable by writing its type (
int in this case), its identifier, and then assigning a value to that variable. The equals sign (
=) is the operator for assignment. You're not defining an equation in a mathematical sense; you're telling the compiler to set the contents of the variable on the left of the operator to the value of whatever is on the right of the operator. In this specific case, you're saying "
myVariable is an
int, and it's assigned the value of
15." There are other operators, and we'll cover them in Chapter 4, but you need to know about assignment now because variables aren't much good without it.
An identifier is just an arbitrary name you assign to a variable, method, class, or other element. In this case, the variable's identifier is
You can define variables without initializing them; just leave off the assignment and the value:
You can then assign a value to
myVariable later in your program:
int myVariable; // some other code here myVariable = 15; // assign 15 to myVariable
You can also change the value of a variable later in the program. That is why they're called variables; their values can vary, and that's what makes them useful.
int myVariable; ...