Home > Articles > Programming > C#

  • Print
  • + Share This
This chapter is from the book

This chapter is from the book

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.

NOTE

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.

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
 2: //   of a variable
 3: //---------------------------------------------------------
 4: 
 5: using System;
 6: 
 7: class var_values
 8: {
 9: public static void Main()
10: {
11:  // declare my_variable
12:  int my_variable;
13: 
14:  // assign a value to my_variable
15:  my_variable = 5;
16:  Console.WriteLine("\nmy_variable contains the value {0}",    
     my_variable);
17: 
18:  // assign a new value to my_variable
19:  my_variable = 1010; 
20:  Console.WriteLine("\nmy_variable contains the value {0}",    
     my_variable);
21: }

22: }

Output
my_variable contains the value 5

my_variable contains the value 1010
Analysis

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.

NOTE

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;

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.
 3: //---------------------------------------------------------
 4: 
 5: using System;
 6: 
 7: class multi_variables
 8: {
 9: public static void Main()
10: {
11:  // declare the variables
12:  int my_variable = 8, your_variable = 1000;
13: 
14:  // print the original value of my_variable
15:  Console.WriteLine("my_variable was assigned the value {0},    
     my_variable);
16:
17:  // assign a value to my_variable
18:  my_variable = 5;
19: 
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);
23: }

24: }

Output
my_variable was assigned the value 8

my_variable contains the value 5

your_variable contains the value 1000
Analysis

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.

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!!
 3: //---------------------------------------------------------
 4: 
 5: using System;
 6: 
 7: class blank
 8: {
 9: public static void Main()
10: {
11:  int blank_variable;
12: 
13:  Console.WriteLine("\nmy_variable contains the value {0}", 
     blank_variable);
14: }
15: }
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.

NOTE

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.

  • + Share This
  • 🔖 Save To Your Account