4.31 Mб


Day 3


A variable is a named data storage location in your computer’s memory. By using a variable’s name in your program, you are, in effect, referring to the information stored there. For example, you could create a variable called my_variable that holds a number. You would be able to store different numbers in the my_variable variable.

You could also create variables to store information other than a simple number. You could create a variable called BankAccount to store a bank account number, a variable called email to store an email address, or a variable called address to store a person’s mailing address. Regardless of what type of information will be stored, a variable is used to obtain its value.

Variable Names

To use variables in your C# programs, you must know how to create variable names. In C#, variable names must adhere to the following rules:

The name can contain letters, digits, and the underscore character (_).

The first character of the name must be a letter. The underscore is also a legal first character, but its use is not recommended at the beginning of a name. An underscore is often used with special commands, and it’s sometimes hard to read.

Case matters (that is, upperand lowercase letters). C# is case-sensitive; thus, the names count and Count refer to two different variables.

C# keywords can’t be used as variable names. Recall that a keyword is a word that is part of the C# language. (A complete list of the C# keywords can be found in Appendix B, “C# Keywords.”)

The following list contains some examples of valid and invalid C# variable names:

Variable Name









Legal, but not advised


Illegal; contains the illegal character #


Illegal; is a C keyword


Illegal; first character is a digit

Storing Information with Variables


Because C# is case-sensitive, the names percent, PERCENT, and Percent are considered three different variables. C# programmers commonly use only lowercase letters in variable names, although this isn’t required. Often, programmers use mixed case as well. Using all-uppercase letters is usually reserved for the names of constants (which are covered later today).

Variables can have any name that fits the rules listed previously. For example, a program


that calculates the area of a circle could store the value of the radius in a variable named


radius. The variable name helps make its usage clear. You could also have created a


variable named x or even billy_gates; it doesn’t matter. Such a variable name, however,


wouldn’t be nearly as clear to someone else looking at the source code. Although it


might take a little more time to type descriptive variable names, the improvements in


program clarity make it worthwhile.


Many naming conventions are used for variable names created from multiple words.

Consider the variable name circle_radius. Using an underscore to separate words in a variable name makes it easy to interpret. Another style is called Pascal notation. Instead of using spaces, the first letter of each word is capitalized. Instead of circle_radius, the variable would be named CircleRadius. Yet another notation that is growing in popularity is Camel notation. Camel notation is like Pascal notation, except the first letter of the variable name is also lower case. A special form of Camel notation is called Hungarian notation. With Hungarian notation, you also include information in the name of the variable—such as whether it is numeric, has a decimal value, or is text—that helps to identify the type of information being stored. The underscore is used in this book because it’s easier for most people to read. You should decide which style you want to adopt.


DO use variable names that are descriptive.

DO adopt and stick with a style for naming your variables.


DON’T name your variables with all capital letters unnecessarily.


C# supports a Unicode character set, which means that letters from any language can be stored and used. You can also use any Unicode character to name your variables.


Day 3

Using Variables

Before you can use a variable in a C# program, you must declare it. A variable declaration tells the compiler the name of the variable and the type of information the variable will be used to store. If your program attempts to use a variable that hasn’t been declared, the compiler will generate an error message.

Declaring a variable also enables the computer to set aside memory for it. By identifying the specific type of information that will be stored in a variable, you gain the best performance and avoid wasting memory.

Declaring a Variable

A variable declaration has the following form:

typename varname;

typename specifies the variable type. In the following sections you will learn about the types of variables that are available in C#. varname is the name of the variable. To declare a variable that can hold a standard numeric integer, you use the following line of code:

int my_number;

The name of the variable declared is my_number. The data type of the variable is int. As you will learn in the following section, the type int is used to declare integer variables, which is perfect for this example!

You can also declare multiple variables of the same type on one line by separating the variable names with commas. This enables you to be more concise in your listings. Consider the following line:

int count, number, start;

This line declares three variables: count, number, and start. Each of these variables is type int, which is for integers.


Although declaring multiple variables on the same line can be more concise, I don’t recommend that you always do this. There are times when it is easier to read and follow your code by using multiple declarations. There will be no noticeable performance loss by doing separate declarations.

Storing Information with Variables


Assigning Values to Variables

Now that you know how to declare a variable it is important to learn how to store values. After all, the purpose of a variable is to store information!

The format for storing information in a variable is

varname = value;

You have already seen that varname is the name of the variable. value is the value that will be stored in the variable. For example, to store the number 5 in the variable, my_variable, you enter the following:

my_variable = 5;

To change the value, you simply reassign a new value:


my_variable = 1010;

Listing 3.1 illustrates assigning values to a variable. It also shows that you can overwrite a value.

LISTING 3.1 var_values.cs—Assigning Values to a Variable

1:// var_values.cs - A listing to assign and print the value



of a variable








using System;





7:class var_values


9:public static void Main()


11:// declare my_variable

12:int my_variable;


14:// assign a value to my_variable

15:my_variable = 5;

16:Console.WriteLine(“\nmy_variable contains the value {0}”,my_variable);


18:// assign a new value to my_variable

19:my_variable = 1010;

20:Console.WriteLine(“\nmy_variable contains the value {0}”,my_variable);





Day 3

my_variable contains the value 5

my_variable contains the value 1010

Enter this listing into your editor, compile it, and execute it. If you need a refresher on how to do this, refer to Day 1, “Getting Started with C#.” The first

three lines of this listing are comments. Lines 11, 14, and 18 also contain comments. Remember that comments provide information; the compiler will ignore them. Line 5 includes the System namespace which you need to do things such as writing information. Line 7 declares the class that will be your program (var_values). Line 9 declares the entry point for your program, the Main() function. Remember, Main() has to be capitalized or you’ll get an error!

Line 12 is the beginning point of today’s lesson. Line 12 declares a variable called my_variable of type integer (int). After this line has executed, the computer knows that a variable called my_variable exists and it enables you to use it. In line 15 you use this variable and assign the value of 5 to my_variable. In line 16 you use Console.WriteLine to display the value of my_variable. As you can see in the output, the value 5—which was assigned in line 15—is displayed. In line 19 you change the value of my_variable from 5 to 1010. You see that this new assignment worked because the call to Console.WriteLine in line 20 prints the new value 1010 instead of 5.

After you assign the value 1010 to my_variable in line 19, the value of 5 is gone. From that point, the program no longer knows that 5 ever existed.


You must declare a variable before you can use it. A variable can, however, be declared at almost any place within a listing.

Setting Initial Values in Variables

You might be wondering whether you can assign a value to a variable at the same time you declare it. Yes, you definitely can. In fact, it is good practice to make sure you always initialize a variable at the time you declare it. To initialize my_variable to the value of 8 when you declare it, you combine what you’ve done before:

int my_variable = 8;

Any variable can be initialized when being declared using the following structure:

typename varname = value;

You can also declare multiple variables on the same line and assign values to each of them:

int my_variable = 8, your_variable = 1000;


Storing Information with Variables


This line declares two integer variables called my_variable and your_variable. my_variable is assigned the value of 8 and your_variable is assigned 1000. Notice that these declarations are separated by a comma and that the statement ends with the standard semicolon. Listing 3.2 shows this statement in action.

LISTING 3.2 multi_variables.cs—Assigning More than One Variable

1:// multi_variables.cs

2:// A listing to assign values to more than one variable.


5: using System; 6:

7:class multi_variables





public static void Main()





// declare the variables



int my_variable = 8, your_variable = 1000;





14:// print the original value of my_variable

15:Console.WriteLine(“my_variable was assigned the value {0},my_variable);


17:// assign a value to my_variable

18:my_variable = 5;


20:// print their values

21:Console.WriteLine(“\nmy_variable contains the value {0}”,my_variable);

22:Console.WriteLine(“\nyour_variable contains the value {0}”,your_variable);



my_variable was assigned the value 8

my_variable contains the value 5

your_variable contains the value 1000

This listing declares and initializes two variables on line 12. The variable, my_variable, is initialized to the value of 8 and the variable, your_variable, is

initialized to the value of 1000. Line 15 prints the value of my_variable so you can see what it contains. Looking at the output, you see that it contains the value 8, which was just assigned.


Day 3

In line 18, the value of 5 is assigned to my_variable. Lines 21 and 22 print the final values of the two variables. The value of my_variable is printed as 5. The original value of 8 is gone forever! your_variable still contains its original value of 1000.

Using Uninitialized Variables

What happens if you try to use a variable without initializing it? Consider the following:

int blank_variable;

Console.WriteLine(“\nmy_variable contains the value {0}”, blank_variable);

In this snippet of code, blank_variable is printed in the second line. What is the value of blank_variable? This variable was declared in the first line, but it was not initialized to any value. You’ll never know what the value of blank_variable is because the compiler will not create the program. Listing 3.3 proves this.

LISTING 3.3 blank.cs—Using an Uninitialized Variable

1:// blank.cs – Using unassigned variables.

2:// This listing causes an error!!


5: using System; 6:

7:class blank


9:public static void Main()


11:int blank_variable;

13:Console.WriteLine(“\nmy_variable contains the value {0}”,blank_variable);



ANALYSIS This program will not compile. Rather, the compiler will give you the following error:

blank.cs(13,67): error CS0165: Use of unassigned local variable ‘blank_variable’

C# will not let you use an uninitialized variable.


In other languages, such as C and C++, this listing would compile. The value printed for the blank_variable in these other languages would be garbage. C# prevents this type of error from occurring.