Home > Articles > Programming > C#

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.


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: //---------------------------------------------------------
 5: using System;
 7: class var_values
 8: {
 9: public static void Main()
10: {
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}",    
18:  // assign a new value to my_variable
19:  my_variable = 1010; 
20:  Console.WriteLine("\nmy_variable contains the value {0}",    
21: }

22: }

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;

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: //---------------------------------------------------------
 5: using System;
 7: class multi_variables
 8: {
 9: public static void Main()
10: {
11:  // declare the variables
12:  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},    
17:  // assign a value to my_variable
18:  my_variable = 5;
20:  // print their values
21:  Console.WriteLine("\nmy_variable contains the value {0}",    
22:  Console.WriteLine("\nyour_variable contains the value {0}",    
23: }

24: }

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.

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

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.

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information

To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.


Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.


If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information

Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.


This site is not directed to children under the age of 13.


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information

If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information

Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents

California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure

Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact

Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice

We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020