Module 4: Data Types and Variables

Similar documents
Module 6: Fundamentals of Object- Oriented Programming

Module 9: Validating User Input

Unit 4. Lesson 4.1. Managing Data. Data types. Introduction. Data type. Visual Basic 2008 Data types

Module 8: Building a Windows Forms User Interface

Introduce C# as Object Oriented programming language. Explain, tokens,

Lab Answer Key for Module 1: Creating Databases and Database Files

Uka Tarsadia University MCA ( 3rd Semester)/M.Sc.(CA) (1st Semester) Course : / Visual Programming Question Bank

IT 374 C# and Applications/ IT695 C# Data Structures

C#: framework overview and in-the-small features

.Net Technologies. Components of.net Framework

Lab Answer Key for Module 8: Implementing Stored Procedures

Agenda & Reading. VB.NET Programming. Data Types. COMPSCI 280 S1 Applications Programming. Programming Fundamentals

Chapter 1 Getting Started

2. A GUI A. uses buttons, menus, and icons B. should be easy for a user to manipulate C. both (a) and (b) D. stands for Graphic Use Interaction

Introduction To C#.NET

Hierarchical inheritance: Contains one base class and multiple derived classes of the same base class.

UNIT 1. Introduction to Microsoft.NET framework and Basics of VB.Net

Microsoft Visual Basic 2005: Reloaded

Microsoft Visual Basic 2015: Reloaded

CS201 - Introduction to Programming Glossary By

Darshan Institute of Engineering & Technology for Diploma Studies

C#.Net. Course Contents. Course contents VT BizTalk. No exam, but laborations

Programming Language 2 (PL2)

VARIABLES. 1. STRINGS Data with letters and/or characters 2. INTEGERS Numbers without decimals 3. FLOATING POINT NUMBERS Numbers with decimals

Short Notes of CS201

Introduction to Programming Using Java (98-388)

BASIC ELEMENTS OF A COMPUTER PROGRAM

Question And Answer.

Java Primer 1: Types, Classes and Operators

SKILL AREA 306: DEVELOP AND IMPLEMENT COMPUTER PROGRAMS

CS313D: ADVANCED PROGRAMMING LANGUAGE

Bit (0, 1) Byte (8 bits: 0-255) Numeral systems. Binary (bin) 0,1 Decimal (dec) 0, 1, 2, 3, Hexadecimal (hex) 0, 1, 2, 3, 1/13/2011

Contents. Figures. Tables. Examples. Foreword. Preface. 1 Basics of Java Programming 1. xix. xxi. xxiii. xxvii. xxix

Objectives. Introduce the core C# language features class Main types variables basic input and output operators arrays control constructs comments

C# Fundamentals. Hans-Wolfgang Loidl School of Mathematical and Computer Sciences, Heriot-Watt University, Edinburgh

Microsoft Exchange Server SMTPDiag

Hands-On Lab. Lab Manual HOL007 Understanding, Designing, and Refactoring Code Using the New Class Designer Tool in Microsoft Visual Studio 2005

Objectives. Describe ways to create constants const readonly enum

Vba Variables Constant and Data types in Excel

C# Types. Industrial Programming. Value Types. Signed and Unsigned. Lecture 3: C# Fundamentals

Tokens, Expressions and Control Structures

Industrial Programming

Computers and Programming Section 450. Lab #1 C# Basic. Student ID Name Signature

Pace University. Fundamental Concepts of CS121 1

Chapter-8 DATA TYPES. Introduction. Variable:

Hands-On Lab. Lab Manual HOLDEV083 Advanced Language Features in Visual Basic

Object-Oriented Programming

Understand Computer Storage and Data Types

CS313D: ADVANCED PROGRAMMING LANGUAGE

Module 5: Programming with C#

Objectives. Chapter 2: Basic Elements of C++ Introduction. Objectives (cont d.) A C++ Program (cont d.) A C++ Program

Chapter 2: Basic Elements of C++

Chapter 2: Basic Elements of C++ Objectives. Objectives (cont d.) A C++ Program. Introduction

Lesson 06 Arrays. MIT 11053, Fundamentals of Programming By: S. Sabraz Nawaz Senior Lecturer in MIT Department of MIT FMC, SEUSL

CSC Web Programming. Introduction to JavaScript

Java How to Program, 10/e. Copyright by Pearson Education, Inc. All Rights Reserved.

CHAPTER 7 OBJECTS AND CLASSES

2007 MICROSOFT OFFICE SYSTEM USER INTERFACE DESIGN GUIDELINES PREVIEW

Module 7: Automating Administrative Tasks

C++\CLI. Jim Fawcett CSE687-OnLine Object Oriented Design Summer 2017

Data Types, Variables and Arrays. OOC 4 th Sem, B Div Prof. Mouna M. Naravani

Module 2: Introduction to a Managed Execution Environment

UNIT- 3 Introduction to C++

CS313D: ADVANCED PROGRAMMING LANGUAGE

Chapter 6 Introduction to Defining Classes

Index. object lifetimes, and ownership, use after change by an alias errors, use after drop errors, BTreeMap, 309

Absolute C++ Walter Savitch

CE221 Programming in C++ Part 1 Introduction

Duhok Polytechnic University Amedi Technical Institute/ IT Dept. Halkawt Rajab Hussain

PROGRAMMING IN VISUAL BASIC WITH MICROSOFT VISUAL STUDIO Course: 10550A; Duration: 5 Days; Instructor-led

Module 3: Managing Groups

Microsoft Dynamics GP Release Integration Guide For Microsoft Retail Management System Headquarters

Object-Oriented Programming in C# (VS 2015)

Microsoft. Microsoft Visual C# Step by Step. John Sharp

CS 231 Data Structures and Algorithms, Fall 2016

This tutorial has been prepared for the beginners to help them understand basics of c# Programming.

Getting started 7. Storing values 21. Creating variables 22 Reading input 24 Employing arrays 26 Casting data types 28 Fixing constants 30 Summary 32

Visual C# Instructor s Manual Table of Contents

Object-Oriented Programming in C# (VS 2012)

Control Flow. COMS W1007 Introduction to Computer Science. Christopher Conway 3 June 2003

C# Programming in the.net Framework

Exercise: Using Numbers

VISUAL BASIC 2005 EXPRESS: NOW PLAYING

DigiPen Institute of Technology

Java How to Program, 10/e. Copyright by Pearson Education, Inc. All Rights Reserved.

Appendix G: Writing Managed C++ Code for the.net Framework

PART I. Part II Answer to all the questions 1. What is meant by a token? Name the token available in C++.

Introduction to Data Entry and Data Types

Procedures in Visual Basic

Excel VBA Variables, Data Types & Constant

Introduction Primitive Data Types Character String Types User-Defined Ordinal Types Array Types. Record Types. Pointer and Reference Types

Programming for the Web with PHP

Chapter 2 Basic Elements of C++

Course Hours

COPYRIGHTED MATERIAL. Contents. Part I: C# Fundamentals 1. Chapter 1: The.NET Framework 3. Chapter 2: Getting Started with Visual Studio

Introduction to.net, C#, and Visual Studio. Part I. Administrivia. Administrivia. Course Structure. Final Project. Part II. What is.net?

Chapter 2. Building Multitier Programs with Classes The McGraw-Hill Companies, Inc. All rights reserved. McGraw-Hill

Lesson 02 Working with Data Types. MIT 31043: VISUAL PROGRAMMING By: S. Sabraz Nawaz Senior Lecturer in MIT

Fig 1.1.NET Framework Architecture Block Diagram

Definition: Data Type A data type is a collection of values and the definition of one or more operations on those values.

Transcription:

Module 4: Data Types and Variables Table of Contents Module Overview 4-1 Lesson 1: Introduction to Data Types 4-2 Lesson 2: Defining and Using Variables 4-10 Lab:Variables and Constants 4-26 Lesson 3: Defining and Using Collections 4-31 Lesson 4: Converting Data Types 4-41 Lab:Arrays and Enumerations 4-49 Lab Discussion 4-54

Information in this document, including URL and other Internet Web site references, is subject to change without notice. Unless otherwise noted, the example companies, organizations, products, domain names, e-mail addresses, logos, people, places, and events depicted herein are fictitious, and no association with any real company, organization, product, domain name, e-mail address, logo, person, place, or event is intended or should be inferred. Complying with all applicable copyright laws is the responsibility of the user. Without limiting the rights under copyright, no part of this document may be reproduced, stored in or introduced into a retrieval system, or transmitted in any form or by any means (electronic, mechanical, photocopying, recording, or otherwise), or for any purpose, without the express written permission of Microsoft Corporation. The names of manufacturers, products, or URLs are provided for informational purposes only and Microsoft makes no representations and warranties, either expressed, implied, or statutory, regarding these manufacturers or the use of the products with any Microsoft technologies. The inclusion of a manufacturer or product does not imply endorsement of Microsoft of the manufacturer or product. Links are provided to third party sites. Such sites are not under the control of Microsoft and Microsoft is not responsible for the contents of any linked site or any link contained in a linked site, or any changes or updates to such sites. Microsoft is not responsible for Webcasting or any other form of transmission received from any linked site. Microsoft is providing these links to you only as a convenience, and the inclusion of any link does not imply endorsement of Microsoft of the site or the products contained therein. Microsoft may have patents, patent applications, trademarks, copyrights, or other intellectual property rights covering subject matter in this document. Except as expressly provided in any written license agreement from Microsoft, the furnishing of this document does not give you any license to these patents, trademarks, copyrights, or other intellectual property. 2007 Microsoft Corporation. All rights reserved. Microsoft, Access, Active Directory, BizTalk, DirectX, Excel, IntelliSense, Internet Explorer, MSDN, Outlook, PowerPoint, SQL Server, Visual Basic, Visual C#, Visual C++, Visual J#, Visual Studio, Win32, Windows, Windows CardSpace, Windows NT, Windows Server, Windows Vista, and WinFX are either registered trademarks or trademarks of Microsoft Corporation in the United States and/or other countries. The names of actual companies and products mentioned herein may be the trademarks of their respective owners. Version 1.1

Module 4: Data Types and Variables 4-1 Module Overview This module provides the second part of the introduction to programming concepts. Data types and variables are two fundamental and related items that are present in virtually all Microsoft.NET Framework applications. This module describes data types, variables, collections, and data type conversion. It then demonstrates the various ways you can use them. Objectives After completing this module, you will be able to: Explain the main features of data types. Define and use variables. Define and use collections. Explain data type conversion.

4-2 Module 4: Data Types and Variables Lesson 1: Introduction to Data Types The data type of a programming element refers to the kind of data it can hold and how that data is stored. The.NET Framework has many different types of values that you can store and process. This lesson explains the main features of data types. Objectives After completing this lesson, you will be able to: Describe the common type system. Explain the difference between value types and reference types. List the predefined data types. Describe guidelines for choosing a data type.

Module 4: Data Types and Variables 4-3 What Is the Common Type System? When you declare a variable to store data in an application, you need to choose an appropriate data type for that data. Microsoft Visual C# and Microsoft Visual Basic are type-safe languages. This means that the compiler guarantees that values stored in variables are always of the appropriate type. Definition of the Common Type System The common type system defines a set of data types that you can use to declare your variables. Each data type corresponds directly to a type defined in the common type system. The common type system contains value types and reference types. Features of the Common Type System The common type system provides cross-language integration and is of fundamental importance when you create applications with the Microsoft.NET Framework. For example, you can create a project in Visual C#, integrate it with a component written in Visual Basic, and use methods written in another.net-compatible language. The common language runtime (CLR), compilers, and tools in Microsoft Visual Studio 2005 all rely on the common type system to provide the following features: Cross-language integration Type-safe code High-performance code execution Without the common type system, you would need to write complex and lengthy code to integrate your cross-language components and ensure type safety.

4-4 Module 4: Data Types and Variables What Are Value Types and Reference Types? The types in the common type system are divided into two categories: value types and reference types. For example, an integer is a value type and a string is a reference type. Most of the predefined types are value types. Value Types Value type variables directly contain their data and are stored in an area of memory called the stack. Assigning one value type variable to another copies the contained value. You can define new value types by creating structures or enumerations or by inheriting from System.ValueType. Value types cannot contain a null value, but the nullable types feature does allow values types to be assigned to null. Examples of value types are integers, Booleans, and characters. Value types have the following main features: They directly contain their data. They are stored on the stack. They should be initialized. They cannot contain a null value. They inherit from System.ValueType. Reference Types Reference types are a reference to a value and are also stored in the stack. They contain a reference to their data, which is stored in an area of memory called the heap. Therefore, it is possible for operations on one reference type variable to affect other variables that refer to the same item of data. Reference types can contain a null value. Null values are useful

Module 4: Data Types and Variables 4-5 when you work with databases and other data types that contain elements that may not be assigned a value. Examples of reference types are strings, classes, and interfaces. Reference types have the following main features: They contain a reference to their data. They are stored on the heap. They can contain a null value. They are instantiated by using the new (Visual C#) or New (Visual Basic) keyword. They inherit from System.Object.

4-6 Module 4: Data Types and Variables Predefined Data Types The common type system includes a set of predefined data types. You can use these predefined data types when you create variables to store information in your code. Predefined data types are either value types or reference types. Definition of Predefined Data Types Predefined data types are divided into three categories: Numeric Numeric data types handle numbers in various representations. Integral types represent whole numbers. Non-integral types represent both integers and decimals. Character Character data types deal with printable and displayable characters. They can be a single character or a string of characters. Specialized Specialized data types deal with specialized data such as true/false values and date/time values.

Module 4: Data Types and Variables 4-7 Commonly Used Data Types The following table shows the commonly used data types and their characteristics. Data type C# VB Description Size (bytes) Range int Integer Whole numbers 4-2,147,483,648 to 2,147,483,647 Value or Reference Value byte Byte Byte 1 0 to 255 Value long Long Whole numbers (bigger range) float Single Floating-point numbers double Double Double precision (more accurate) floating-point numbers 8-9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 4 +/- 1.5 x 10^ 45 to 3.4 x 10^38 with a precision of 7 digits 8 +/- 5.0 x 10^ 324 to 1.7 x 10^308 with a precision of 15-16 digits. Value Value Value decimal Decimal Monetary values 16 28 significant figures Value char Char Single character 2 N/A Value bool Boolean Boolean 1 True or false Value DateTime DateTime Moments in time 8 0:00:00 on 01/01/2001 to 23:59:59 on 12/31/9999 string String Sequence of characters 2 per character object Object Generic object 4 (32-bit) or 8 (64- bit) N/A N/A Value Reference Reference

4-8 Module 4: Data Types and Variables Guidelines for Choosing a Data Type The data type determines the allowable values for a variable. This in turn determines the operations that can you can perform on the variable. The list of different data types can seem overwhelming, but you can follow these guidelines to help you choose the correct data type. Choosing a Data Type You may require number data types with specific precision for some applications. You may also require string data. The following table contains guidelines to help you choose among the available data types according to data type category. Category Guidelines Numeric For counters or simple whole numbers, use the int (Visual C#) or Integer (Visual Basic) data type. For numbers with decimal places, use the float (Visual C#) or Single (Visual Basic) data type. If you require more precision, use the double (Visual C#) or Double (Visual Basic) data type. For monetary values, use the decimal (Visual C#) or Decimal (Visual Basic) data type. Character For single characters, use the char (Visual C#) or Char (Visual Basic) data type. For single strings, use the string (Visual C#) or String (Visual Basic) data type. For the creation and manipulation of strings, use the StringBuilder class. The StringBuilder class provides a very efficient way to create and manipulate strings. However, strings are used throughout this course for simplicity. Specialized For any date or time values, use the System.DateTime data type or the Date (Visual Basic) keyword. For yes/no or true/false values, use the bool (Visual C#) or Boolean

Module 4: Data Types and Variables 4-9 Category Guidelines (Visual Basic) data type. Strong Typing When you declare a variable in Visual C#, you must state the variable data type. In Visual Basic, you can declare a variable without a data type and the variable is assigned the Object data type by default. This ability to not type your variables in Visual Basic makes it quick and easy to write applications. However, it can cause performance and typing issues. Specifying the data type for all your variables is known as strong typing. You should use strong typing for the following reasons: It minimizes memory usage. It allows the compiler to perform type checking. It results in faster execution of your code. It enables Microsoft IntelliSense support for your variables. In Visual Basic, Option Strict is set to Off by default. You can set Option Strict to On to enforce strong typing.

4-10 Module 4: Data Types and Variables Lesson 2: Defining and Using Variables When you develop applications, you often need to store static or dynamic data. You can use variables, constants, and enumerations to store this data. This lesson describes how to define and use variables, constants, and enumerations. Objectives After completing this lesson, you will be able to: Describe variables and constants. Explain how to declare variables. Explain how to assign values to variables. Explain how to declare constants. Explain variable scope. Describe how to define variables at different scope levels. Describe how to create and use enumeration types.

Module 4: Data Types and Variables 4-11 What Are Variables and Constants? Variables store values required by the application in temporary memory locations. Applications process these values to perform functions such as calculations, data analysis, and database interactions. Constants are simply variables with a constant value. Applications use constants in situations where a value has a fixed number, such as the number of minutes in an hour or the radius of the earth. Definition of Variables Variables store values that can change when an application is running. You often need to store values temporarily when you perform calculations or pass data between the user and the application or the application and a database. For example, you might want to retrieve several values, compare them, and perform different operations on them depending on the result of the comparison. A variable has the following six elements: Name. Unique identifier that refers to the variable in code. Address. Memory location of the variable. Data type. Type and size of data the variable can store. Value. Value at the address of the variable. Scope. Defined areas of code that can access and use the variable. Lifetime. Period of time that a variable is valid and available for use. Examples of Variables You can use variables in many ways. These ways include the following: As a counter for loop structures.

4-12 Module 4: Data Types and Variables As temporary storage for property values. To hold a value returned from a method. As a location to store directory or file names. Definition of Constants Constants store values that do not change when an application is running. The value is computed at compile time and cannot be changed by the application. If a variable in your program contains a value that never changes, you should store the value as a constant instead of a variable. Constants use less memory than variables because constants are hard-coded into the MSIL (Microsoft Intermediate Language). Advantages of constants include the following: Code is easier to read. Constants use less memory than variables. Application-wide changes are easier to implement. Examples of Constants You can use constants for many values. These values include the following: Hours in a day Speed of light Degrees in a circle VAT rate

Module 4: Data Types and Variables 4-13 How to Declare Variables Before you can use a variable, you must declare it to specify its name and characteristics. When you declare a variable, you reserve some storage space for that variable in memory. Variables that are declared at method or property level are called local variables. Syntax When you declare variables, you must specify what type of data it will hold. You can use the comma separator to declare multiple variables in a single declaration. The syntax of a variable declaration and a multiple variable declaration is shown in the following example. DataType variablename; DataType variablename1, variablename2... ; Dim variablename As DataType Dim variablename1 As DataType, variablename2 As DataType... When you declare a reference type variable, you should also use the new (Visual C#) or New (Visual Basic) keyword to create the variable and invoke its constructor. The syntax of a reference type variable declaration is shown in the following example. DataType variablename = new DataType(); Dim variablename As DataType = New DataType()

4-14 Module 4: Data Types and Variables Example The following example declares an integer variable called counter. int counter; Dim counter As Integer

Module 4: Data Types and Variables 4-15 How to Assign Values to Variables After you have declared a variable, you can assign a value to it for later use in the application. You can also assign a value to a variable at the same time as you declare the variable. You can change the value in a variable as many times as you want at run time. Syntax The assignment operator (=) assigns a value to a variable. The syntax for a variable assignment is shown in the following example. variablename = Value; variablename = Value The value on the right side of the expression is assigned to the variable on the left side of the expression. The syntax of a combined variable declaration and assignment is shown in the following example. DataType variablename = Value; Dim variablename As DataType = Value In Visual Basic, when you use the Dim statement to create a variable, Visual Basic automatically performs the following tasks: Initializes numerical variables to 0.

4-16 Module 4: Data Types and Variables Initializes, text strings to empty (""). Initializes date variables to January 1, 0001. Examples The following example declares an integer called price and assigns the number 10 to the integer. int price = 10; Dim price As Integer = 10 The following example assigns the number 20 to an existing integer called price. price = 20; price = 20

Module 4: Data Types and Variables 4-17 How to Declare Constants Constants make your code more readable, maintainable, and robust. For example, when you use a constant in a calculation, it is immediately apparent what value you are referring to. You define constants at design time and you cannot assign a different value to constants at run time. Syntax To declare a constant, use the const (Visual C#) or Const (Visual Basic) keyword and specify a type. You must assign a value to your constants when you declare them. The syntax of a variable assignment is shown in the following example. const DataType constantname = Value; Const constantname As DataType = Value Example The following example declares a constant called PI to calculate the area and circumference of a circle with a radius of 5.

4-18 Module 4: Data Types and Variables const double PI = 3.14159; int radius = 5; double area = PI * radius * radius; double circumference = 2 * PI * radius; Const PI As Double = 3.14159 Dim radius As Integer = 5 Dim area As Double = PI * radius * radius Dim circumference As Double = 2 * PI * radius

Module 4: Data Types and Variables 4-19 What Is Variable Scope? When you declare variables, you must ensure that they are accessible to all the code that uses them. You may also need to restrict access to certain variables. For example, you may restrict access for security reasons. The set of all code that can refer to a variable by its name is known as the scope of the variable. If you use a variable outside its scope, the compiler will generate an error. Levels of Scope Variables can have one of the following levels of scope: Block. Available only within the code block in which it is declared. A block is a set of statements enclosed within initiating and terminating declaration statements. Procedure. Available only within the property or method in which it is declared. Module. Available to all code within the module, class, or structure in which it is declared. Namespace. Available to all code in the namespace. These levels of scope progress from the narrowest (block) to the widest (namespace). The narrowest scope is the smallest set of code that can refer to a variable without qualification. Access Levels To set the access level for a variable, you add the appropriate keyword to the variable declaration. The following table shows the access modifiers that you can add to your variables at the time of declaration to control their scope.

4-20 Module 4: Data Types and Variables Keyword Visual C# Visual Basic Description public Public Access is not limited. Any other class can access a public variable. private Private Access is limited to the containing type. Only the class containing the variable can access the variable. internal Friend Access is limited to this assembly. Classes within the same assembly can access the variable. protected Protected Access is limited to the containing class and to types derived from the containing class. protected internal Protected Friend Access is limited to the containing class, derived classes, or to classes within the same assembly as the containing class. Factors That Affect Scope When you declare a variable, you can assign the variable scope. There are three main factors that affect variable scope. These factors are as follows: Location of declaration. The declaration can be inside a block, procedure, module, class, or structure. Scope of container. The scope of a variable cannot exceed the scope of its container. Access modifier of variable. The syntax you use to declare the variable.

Module 4: Data Types and Variables 4-21 How to Define Variables at Different Scope Levels When you declare a variable, you should keep the scope of the variable as narrow as possible. This helps to conserve memory and minimizes the chance that your code references the wrong variable. The scope of a variable cannot be greater than the scope of its container. Block Scope A block is a set of statements enclosed in initiating and terminating declaration statements, such as a loop. If you declare a variable in a block, you can use it only in that block. The lifetime of the variable is still that of the entire procedure. The following example shows how to set a local variable called area with block-level scope if the parameter length is greater than 10. public int CalculateArea(int length) { int area = 0; if (length > 10) { area = length * length; } return area; } Public Function CalculateArea(ByVal length As Integer) Dim area As Integer = 0 If length > 10 Then area = length * length End If Return area

4-22 Module 4: Data Types and Variables End Function Procedure Scope Variables you declare within a procedure are not available outside that procedure. Only the procedure that contains the declaration can use the variable. When you declare variables in a block or procedure, they are known as local variables. The following example shows how to declare a local variable called name with procedure-level scope. void ShowName() { string name = "Bob"; MessageBox.Show("Hello " + name); } Sub ShowName() Dim name As String = "Bob" MessageBox.Show("Hello " & name) End Sub Module Scope If you want the scope of a local variable to extend beyond the scope of the procedure, declare the variable at module-level scope. When you declare variables in a module, class, or structure, but not inside a procedure, they are known as member variables or fields. You can use an access modifier to assign a scope to module variables. The following example shows how to declare a local variable called message with module-level scope. private string message; void SetString() { message = "Hello World!"; } void ShowString() { MessageBox.Show(message); } Private message As String Sub SetString() message = "Hello World!" End Sub Sub ShowString() MessageBox.Show(message) End Sub

Module 4: Data Types and Variables 4-23 Namespace Scope When you use the public (Visual C#) or Public (Visual Basic) keyword to declare variables at module level, they are available to all procedures in the namespace. You can also declare variables with the internal (Visual C#) or Friend (Visual Basic) keyword to make them accessible only from within the same assembly. The following example shows you how to declare a variable called message in one class that you can access in another class. public class CreateMessage { public string Message = "Hello"; } public class DisplayMessage { public void ShowMessage() { // Creates a new instance of the CreateMessage class. CreateMessage newmessage = new CreateMessage(); // Displays the message string of the CreateMessage class. MessageBox.Show(newMessage.Message); } } Public Class CreateMessage Public Message As String = "Hello" End Class Public Class DisplayMessage Public Sub ShowMessage() ' Creates a new instance of the CreateMessage class. Dim newmessage As New CreateMessage() ' Displays the message string of the CreateMessage class. MessageBox.Show(newMessage.Message) End Sub End Class

4-24 Module 4: Data Types and Variables How to Create and Use Enumeration Types Enumerations enable you to use meaningful names instead of simple numerical values. This can simplify code and improve code readability. In situations where you have a set of related constants, you can use an enumeration to enable you to choose from a limited set of values. Definition of Enumerations An enumeration type specifies a set of named constants. An enumeration type is a userdefined type. When you create an enumeration type, you can declare variables of that type and assign values to those variables. You use an enumeration type to represent a set of related constant values. In addition to all the advantages that constants provide, enumerations also have the following benefits: Code is easier to maintain because you assign only anticipated values to your variables. Code is easier to read because you assign easily identifiable names to your values. Code is easier to enter because IntelliSense displays a list of the possible values that you can use. Syntax You use the enum (Visual C#) or Enum (Visual Basic) keyword to create an enumeration type. You must assign a name to the enumeration and then list the values that your enumeration accepts. You can declare enumerations in a class or a namespace but not in a method. The syntax you use to create an enumeration is shown in the following example.

Module 4: Data Types and Variables 4-25 enum Name : DataType { Value1, Value2... }; Enum Name As DataType Value1 Value2... End Enum Enumeration values start from 0 by default. However, you can specify integer literals to initialize an enumeration. Example The following example declares an enumeration for the seasons of the year and specifies the integer literals to start from 1. enum Seasons : int { Spring = 1, Summer = 2, Fall = 3, Winter = 4 }; Enum Seasons As Integer Spring = 1 Summer = 2 Fall = 3 Winter = 4 End Enum

4-26 Module 4: Data Types and Variables Lab: Variables and Constants After completing this lab, you will be able to: Retrieve the current user from a logon form and display the user on another form. Estimated time to complete this lab: 20 minutes Lab Setup For this lab, you will use the available virtual machine environment. Before you begin the lab, you must: Start the 4994A-LON-DEV-04 virtual machine. Log on to the virtual machine with a user name of Student and a password of Pa$$w0rd. Lab Scenario You are a new developer in the Adventure Works organization, a fictitious bicycle manufacturer. You are currently learning how to create a Windows Forms application by working on a version of a sales application. In this lab, you will add further functionality to the current application.

Module 4: Data Types and Variables 4-27 Exercise 1: Implementing Variables and Constants In this exercise, you will add a text box to the MainForm form to display your name. You will declare variables for logon functionality in the LogonForm class. You will implement the OK button event handler to set the corresponding variables and close the LogonForm form. You will also implement the Load event of the MainForm form to display the LogonForm form and retrieve the current user. The principal tasks for this exercise are as follows: Add a text box to the MainForm form. Declare variables in the LogonForm class. Implement the OK button event handler of the LogonForm form. Implement the Load event handler of the MainForm form. Open the AdventureWorksSales application 1. Start Microsoft Visual Studio 2005. 2. On the File menu, point to Open, and then click Project/Solution. 3. In the Open Project dialog box, open the SalesApplication.sln solution file for the starter Sales application. If you are using Visual C#, the solution file is located in the E:\Labfiles\Starter\CS\SalesApplication folder. If you are using Visual Basic, the solution file is located in the E:\Labfiles\Starter\VB\SalesApplication folder. 4. In Solution Explorer, double-click MainForm. The MainForm form is displayed in design view. Add a text box and label to MainForm 1. In the Toolbox, in the Common Controls group, drag a TextBox control to the form. 2. In the Properties window, set the following properties for the text box: (Name): currentusertextbox BorderStyle: FixedSingle Location: 257, 63 ReadOnly: True Size: 150, 20 3. In the Toolbox, in the Common Controls group, drag a Label control to the form. 4. In the Properties window, set the following properties for the label:

4-28 Module 4: Data Types and Variables (Name): currentuserlabel Location: 183, 65 Text: Current User: Declare variables in the LogonForm class 1. In Solution Explorer, double-click LogonForm. 2. On the View menu, click Code. 3. In the LogonForm class, perform the following actions: a. Declare a private string constant to hold a standard welcome message. b. Declare a private Boolean variable to hold a value that indicates whether the user has logged on successfully. Set this variable to false. c. Declare a public user name string variable. d. Declare a private password string variable. Your code should resemble the following. // TODO: Declare variables for the class. private const string welcomemessage = "Welcome to Adventure Works"; private bool isloggedon = false; public string UserName = ""; private string password = ""; ' TODO: Declare variables for the class. Private Const welcomemessage As String = "Welcome to Adventure Works" Private isloggedon As Boolean = False Public UserName As String = "" Private password As String = "" Implement the OK button event handler 1. In the okbutton_click event handler, set the UserName and password string variables to the Text property of the corresponding text boxes. 2. Display a message box that contains the welcome message and user name. 3. Set the Boolean variable to indicate that the user has logged on successfully and close the form. Your code should resemble the following. private void okbutton_click(object sender, EventArgs e) { // Set the user name and password to local variables. UserName = usernametextbox.text; password = passwordtextbox.text;

Module 4: Data Types and Variables 4-29 } // Display a welcome message to the user. MessageBox.Show(welcomeMessage + " " + UserName + "!", "Greetings"); // Set the logon Boolean. isloggedon = true; // Close the form. this.close(); Private Sub okbutton_click(byval sender As System.Object, ByVal e As _ System.EventArgs) Handles okbutton.click ' Set the user name and password to local variables. UserName = usernametextbox.text password = passwordtextbox.text ' Display a welcome message to the user. MessageBox.Show(welcomeMessage & " " & UserName & "!", "Greetings") ' Set the logon Boolean. isloggedon = True ' Close the form. Me.Close() End Sub Implement the Load event handler for MainForm 1. In Solution Explorer, double-click MainForm. 2. In the Designer window, double-click MainForm. This creates an event handler for the Load event of the MainForm form. 3. In the MainForm_Load event handler, create a new instance of the LogonForm form and display the form as a dialog form. This displays the LogonForm form as a modal dialog box. You must close or hide a modal form or dialog box before you can continue working with the rest of the application. 4. Display the user name in the currentusertextbox control. Your code should resemble the following. private void MainForm_Load(object sender, EventArgs e) { // Create a new logon form. LogonForm newlogonform = new LogonForm(); // Display the logon form as a dialog box. newlogonform.showdialog(); // Set the current user text box to the user name on the logon form. currentusertextbox.text = newlogonform.username; } Private Sub MainForm_Load(ByVal sender As System.Object, ByVal e As _ System.EventArgs) Handles MyBase.Load ' Create a new logon form.

4-30 Module 4: Data Types and Variables Dim newlogonform As LogonForm = New LogonForm() ' Display the logon form as a dialog box. newlogonform.showdialog() ' Set the current user text box to the user name on the logon form. currentusertextbox.text = newlogonform.username End Sub Build and test the application 1. On the Build menu, click Build Solution. Verify that the solution builds without any errors. 2. On the Debug menu, click Start Debugging. The LogonForm form displays as a modal dialog box. 3. In the User name box, type your name. 4. In the Password box, type any password of your choice and then click OK. A message box displays a welcome message and your name. 5. In the message box, click OK. This closes the message box and LogonForm form, and then opens the MainForm form. 6. Verify the form displays your name as the current user. 7. Close the application. Results Checklist The following is a checklist of results for you to verify that you have performed this lab successfully. Ensure that you have performed the following tasks: Displayed the current user on the MainForm form. Note: Do not shutdown the virtual machine, because you will use it for the second part of the lab.

Module 4: Data Types and Variables 4-31 Lesson 3: Defining and Using Collections The.NET Framework provides classes that you can use to construct and manipulate collections of objects. This lesson describes collections and some of the commonly used collection types. It also describes how to use arrays and collections. Objectives After completing this lesson, you will be able to: Describe collections. List the commonly used collection types. Explain how to create and use arrays. Define and use collections.

4-32 Module 4: Data Types and Variables What Are Collections? You can handle related data more efficiently when it is grouped together into a collection. A collection is a set of objects that are grouped together and referred to as a unit. For example, items in a list box are part of an Items collection. In the.net Framework, most collection classes are found in two namespaces: System.Array and System.Collections. Definition of Collections Collections are similar to arrays, but provide extra functionality. For example, you can use an index number or key values to easily add and remove items. Additionally, you can create your own collections. You can then add your own elements or existing elements to these collections. An element can be any data type. This includes objects, structures, and other collection objects. The System.Collections namespace contains interfaces and classes that define various collections of objects. These objects can include lists, queues, stacks, and hash tables. These collections provide a variety of data structures that you can use to manage your data. For example, System.Collections.ArrayList represents the ArrayList class, which belongs to the System.Collections namespace. Features of Arrays One type of collection is called an array. An array is a sequence of elements. All elements in an array have the same type. You use an integer index to access the elements of an array. Arrays have the following main features: Every element in the array contains a value. The length of an array is the total number of elements it can contain. The lower bound of an array is the index of its first element.

Module 4: Data Types and Variables 4-33 Arrays can be one dimensional or multidimensional. The rank of an array is the number of dimensions in the array. The System.Array class is the base class of all array types. It contains methods you can use to create, manipulate, search, and sort arrays. The Array class is not part of the Collections namespace. Arrays of a particular type can only hold elements of that type. If you need to manipulate a set of unlike objects or value types, you should use one of the collection types that are defined in the System.Collections namespace.

4-34 Module 4: Data Types and Variables Commonly Used Collection Types Arrays are useful, but they do have limitations. For example, when you create an array, you must know how many elements you need. Additionally, it may not be convenient for your application to use a sequential index to access the element. There are several types of collections. Each type provides slightly different features. Lists, hash tables, queues, and stacks are common ways to manage data in an application. Commonly Used Collections The following table shows some of the classes in the System.Collections namespace. Class SortedList ArrayList BitArray Hashtable Queue Stack Description Represents a sorted collection of key/value pairs of objects. The collection is sorted by the keys. The values are accessible by key or index. This class is less flexible than classes that implement a Sort method. This is because the sort ordering cannot be changed after the class is constructed. Represents a resizable, index-based collection of objects. Items can be inserted or removed at any position. In almost every situation, this class is a good alternative to an array. Manages a compact array of bit values, which are represented as Booleans. A true value indicates that the bit is on (1). A false value indicates the bit is off (0). Represents a collection of key/value pairs that are organized according to the hash code of the key. A hash table uses a hash code to drastically limit the number of objects that must be searched to find a specific object in a collection of objects. Represents a first-in, first-out collection of objects. An element is inserted into the end of the queue and removed from the beginning of the queue. Use a queue when you want hold elements and discard them immediately thereafter, such as information in a buffer. Represents a simple last-in, first-out collection of objects. An element joins the stack at the top and leaves the stack at the top. Use a stack when you need last-

Module 4: Data Types and Variables 4-35 Class Description in, first-out access. For example, you can use a stack to hold items during calculations.

4-36 Module 4: Data Types and Variables How to Create and Use Arrays Arrays are reference type variables, regardless of the type of their elements. Therefore, an array variable refers to an array instance on the heap and does not hold its elements directly on the stack. When you declare an array variable, you do not need to declare the size of the array. You can specify the size when you actually create the array instance. You can also dynamically create the size of an array at run time. Single-Dimension Arrays To declare a single-dimension array, you specify its name, data type, and optionally its size. The size of an array is the number of elements it can contain. Follow the same guidelines for naming, scope, and choice of data type. You can assign a value to a specific element in the array by referring to the index numbers of the element. The declaration syntax of a single-dimension array is shown in the following example. Type[] arrayname = new Type[ Size ]; Dim ArrayName() As Type = New Type( Size ) {} Note: Both Visual C# and Visual Basic use zero-based arrays (where the index begins at zero). However, in Visual Basic, the number in parentheses specifies the upper bound of the array. Therefore, an array declared as (5) will actually consist of six elements, numbered from 0 to 5.

Module 4: Data Types and Variables 4-37 Multidimensional Arrays An array can have more than one dimension. The number of dimensions corresponds to the number of indexes you use to identify an individual element in the array. You can specify up to 32 dimensions, but you will rarely need more than three dimensions. You can declare a multidimensional array variable just as you declare a single-dimension array. However, you use commas to separate the dimensions. The declaration syntax of a multidimensional array is shown in the following example. Type[,,... ] arrayname = new Type[ Size1, Size2,... ]; Dim ArrayName(,,... ) As Type = New Type( Size1, Size2,... ) {} When you add dimensions to an array, the total storage of the array increases dramatically. Therefore, you should not declare an array that is larger than your requirements. You can think of a two-dimensional array as a grid and a three-dimensional array as a cube. Resizing Arrays In Visual Basic, you can resize arrays at any time by using the ReDim keyword to specify new dimensions. You can even use this to change the number of dimensions in the array. You can use the Preserve keyword to retain the current values in the array. If you do not use this keyword, you will lose any current values when you resize the array. Resizing arrays helps you to manage memory efficiently. If you are unsure of the size of array you need, do not specify the size of the dimensions when you declare the array. You can resize the array appropriately at a later time. The following syntax resizes an existing single dimensional array. ReDim Preserve currentarray( NewSize ) In Visual C#, you can use the Array.Resize method to resize single-dimension arrays. Alternatively, you can use one of the existing.net collections. For example, ArrayList handles dynamic resizing automatically. Example The following example creates a single-dimension array and sets the first element of the array to the integer 3. int[] nums = new int[5]; nums[0] = 3; Dim nums() As Integer = New Integer(5) {} nums(0) = 3

4-38 Module 4: Data Types and Variables How to Define and Use Collections You can use collections to store, look up, and iterate over an assortment of objects. Arrays are useful, but applications are much harder to develop without the rich functionality of collections. You must include the System.Collections namespace to use collections. Syntax The following example shows the syntax required to define and use collections. CollectionName objectname = new CollectionName(); objectname.methodname(parameterlist); otherobject = objectname.propertyname; // Constructor. // Methods. // Properties. Dim objectname As New CollectionName() objectname.methodname(parameterlist) otherobject = objectname.propertyname ' Constructor. ' Methods. ' Properties. The CollectionName specifies the name of the collection. Examples are SortedList, ArrayList, BitArray, Hashtable, Queue, and Stack. Apart from the BitArray collection, you do not need to specify size when you initialize any of the above data types. This is because they will expand as required. The BitArray is a resizeable collection, but does not dynamically resize. The following table shows some of the most commonly used methods of these collections. Collection Name Description SortedList Add Adds an element with the specified key and value to a SortedList object.

Module 4: Data Types and Variables 4-39 Collection Name Description GetKey Remove Gets the key at the specified index of a SortedList object. Removes the element with the specified key from a SortedList object. ArrayList Add Adds an object to the end of the ArrayList. Insert Remove Inserts an element into the ArrayList at the specified index. Removes the first occurrence of a specific object from the ArrayList. Hashtable Add Adds an element with the specified key and value into the Hashtable. GetHashCode Remove Serves as a hash function for a particular type. BitArray Not Inverts all the bit values. Or Xor Removes the element with the specified key from the Hashtable. Performs the bitwise OR operation on all elements in the current BitArray against the corresponding elements in the specified BitArray. Performs the bitwise exclusive OR operation on all elements in the current BitArray against the corresponding elements in the specified BitArray. Queue Dequeue Removes and returns the object at the beginning of the queue. Enqueue Adds an object to the end of the queue. Stack Peek Returns the object at the top of the stack without removing it. Push Pop Removes and returns the object at the top of the stack. Inserts an object at the top of the stack. Example The following example creates an ArrayList and manipulates the collection. // Creates a new ArrayList instance. ArrayList carcollection = new ArrayList(); // Add two items to the list. carcollection.add("red Car"); carcollection.add("blue Car"); // Insert an item between the two items in the list. carcollection.insert(1, "Green Car"); // Remove the Red Car item. carcollection.remove("red Car"); ' Creates a new ArrayList instance. Dim carcollection As New ArrayList() ' Add two items to the list. carcollection.add("red Car") carcollection.add("blue Car") ' Insert an item between the two items in the list. carcollection.insert(1, "Green Car")

4-40 Module 4: Data Types and Variables ' Remove the Red Car item. carcollection.remove("red Car") The code adds two string items to the list, inserts another string item between the two items, and then removes the first string item. At the end of the example, the ArrayList contains the items "Green Car" and "Blue Car."

Module 4: Data Types and Variables 4-41 Lesson 4: Converting Data Types Data type conversion is the process of changing a value from one data type to another. You can convert data types by a simple implicit conversion or by explicitly naming the data type. This lesson explains data type conversion. It also explains the differences between implicit and explicit data type conversion. Objectives After completing this lesson, you will be able to: Describe data type conversion. Explain implicit data type conversions. Describe how to use explicit data type conversions.

4-42 Module 4: Data Types and Variables What Is Data Type Conversion? When you design applications, you often need to convert data from one type to another. Conversions are necessary when a value of one type must be assigned to a variable of a different type. The process of converting a value of one data type to another is called conversion or casting. Implicit and Explicit Conversions Both Visual C# and Visual Basic allow you to explicitly convert values from one type to another. The.NET Framework includes two conversion types: Implicit conversion. This is automatically performed by the CLR on operations that are guaranteed to succeed without losing information. Explicit conversion. This requires you to write code to perform a conversion that otherwise could lose information or produce an error. Explicit conversion avoids bugs in your code and makes your code more efficient. Visual Basic also enables you to perform some data type conversions implicitly. This includes implicit conversions that lose precision. Visual C# prohibits implicit conversions that lose precision. However, be aware that implicit conversions can yield unexpected results. Examples of Conversion Functions The two following examples illustrate scenarios where you need to use conversions: A user enters a currency value into a Web page in text format. The developer must then convert that textual value into a numerical value.

Module 4: Data Types and Variables 4-43 A method adds two bytes and returns the result. The result could easily be greater than one byte, so the compiler converts the result to an integer. This avoids number overflow. Conversion functions allow you to explicitly convert a value from one data type to another. Visual Basic provides a set of conversion functions. These functions are shown in the following table. Function Converts to data type Allowable data types for conversion CStr String Any numeric type, Boolean, Char, Date, Object CInt Integer Any numeric type, Boolean, String, Object CDbl Double Any numeric type, Boolean, String, Object CDate Date String Object CType Type specified Same type as allowed for the corresponding conversion function

4-44 Module 4: Data Types and Variables Implicit Data Type Conversions An implicit conversion is when a value is converted automatically from one data type to another. The conversion does not require any special syntax in the source code. Visual Basic allows implicit conversions between types. However, Visual C# allows only safe implicit conversions. Safe implicit conversions include widening of integers and conversion from a derived type to a base type. Example The following example shows how data is converted implicitly from an integer to a long. int a = 4; long b; b = a; // Implicit conversion of int to long. Dim a As Integer = 4 Dim b As Long b = a ' Implicit conversion of Integer to Long. This conversion always succeeds and never results in a loss of information. The following table shows the implicit type conversions that are supported in Visual C#. From sbyte byte short Ushort int To short, int, long, float, double, decimal short, ushort, int, uint, long, ulong, float, double, decimal int, long, float, double, decimal int, uint, long, ulong, float, double, decimal long, float, double, decimal

Module 4: Data Types and Variables 4-45 From uint long, ulong float char To long, ulong, float, double, decimal float, double, decimal double ushort, int, uint, long, ulong, float, double, decimal Disadvantages In Visual Basic, you may experience problems if you rely on implicit conversions to automatically convert variables. Additionally, you can lose data if you use a narrowing conversion. Moreover, implicit conversions result in performance degradation due to the extra work involved. How Option Strict Affects Conversions In Visual Basic, Option Strict is set to Off by default. This allows the implicit declaration of variables. Therefore, all widening and narrowing conversions can implicitly occur. When Option Strict is set to On, only widening conversions are permitted implicitly. Implicit narrowing conversions will generate a compile error. Note: For more information about Option Strict, see the Visual Studio Documentation.

4-46 Module 4: Data Types and Variables How to Use Explicit Conversions Explicit conversions are more efficient than implicit conversions because there is no procedural call to complete the conversion. It is good programming practice to use explicit conversions. Boxing and Unboxing In some cases, you will need to convert between reference and value types. Boxing converts a value type to a reference type. Unboxing converts a reference type to a value type. In Visual C#, you must perform boxing or unboxing with an explicit cast operator. In Visual Basic, you can use conversion functions to perform boxing or unboxing. The following example demonstrates boxing with the explicit conversion of an integer value type to an object reference type. int i = 12; object o = (object) i; Dim i As Integer = 12 Dim o As Object = CType(i, Object) Boxing and unboxing can cause significant performance degradation, especially in loop structures. For example, if you declare an integer variable and assign it to an object variable, the CLR copies the variable, embeds the copy in a newly allocated object, and stores its type information. If your application frequently treats a value type variable as an object, you should initially declare it as a reference type. An alternative is to box the variable once, retain the boxed version as long as it is being used, and then unbox it when the value type is needed again.

Module 4: Data Types and Variables 4-47 The Console.WriteLine method uses boxing in exactly this manner to print text to a console by using the overloaded ToString method. Boxing occurs implicitly when you use a value type where a reference type is expected. Unboxing occurs if you assign a reference object to a value type. The following example demonstrates unboxing. object o = 12; int i = (int) o; Dim o As Object = 12 Dim i As Integer = CType(o, Integer) Syntax In Visual C#, you must use an explicit cast operator to perform explicit conversions. In Visual Basic, you can use conversion functions to perform explicit conversions. The syntax for performing an explicit conversion is shown in the following code. DataType variablename1 = (castdatatype) variablename2; Dim DataType As DataType = CType(variableName2, castdatatype) Widening and Narrowing Conversions Widening conversions do not lose precision because the new data type can contain any possible value of the original data type. For example, you can convert an int (Visual C#) or Integer (Visual Basic) to a long (Visual C#) or Long (Visual Basic). Narrowing conversions can lose precision because the new data type might not be able to hold all the possible values of the original data type. This might happen, for example, if you convert a long (Visual C#) or Long (Visual Basic) to an int (Visual C#) or Integer (Visual Basic). Examples The following example explicitly converts a double (Visual C#) or Double (Visual Basic) to an int (Visual C#) or Integer (Visual Basic). double a = 2.46; int b = (int) y; Dim a As Double = 2.46 Dim b As Integer = CType(a, Integer) This narrowing conversion must be explicit because there is a loss of precision. In the example, the value 2.46 is shorted to 2.

4-48 Module 4: Data Types and Variables System.Convert The System.Convert class provides another way to perform data type conversion. This class uses a set of methods to convert a base data type to another base data type. All languages that target the CLR can use this class. You might find this class easier to use for conversions because IntelliSense helps you locate the conversion method you need. The following example converts a double (Visual C#) or Double (Visual Basic) to a string. double number = 6.42; string numberstring = number.tostring(); number As Double = 6.42 numberstring As String = number.tostring()

Module 4: Data Types and Variables 4-49 Lab: Arrays and Enumerations After completing this lab, you will be able to: Use arrays and enumerations to display the selected values of a control. Estimated time to complete this lab: 20 minutes Lab Setup For this lab, you will use the available virtual machine environment. Before you begin the lab, you must: Continue with the 4994A-LON-DEV-04 virtual machine. Log on to the virtual machine with a user name of Student and a password of Pa$$w0rd. Lab Scenario In this lab, you will continue to add further functionality to the current application.

4-50 Module 4: Data Types and Variables Exercise 1: Implementing Arrays and Enumerations In this exercise, you will create a CheckedListBox control and an enumeration to contain different regions. You will add items to the CheckedListBox control. You will also create an array to store all the regions. You will then display a message box that states which regions are selected in the CheckedListBox control. The principal tasks for this exercise are as follows: Create a CheckedListBox control. Create an enumeration for different regions. Create a string array to store the selected regions of the CheckedListBox control. Display a message box that states which regions are selected. Create a CheckedListBox control 1. In Solution Explorer, double-click MainForm. 2. In the Toolbox, in the Common Controls group, drag a CheckedListBox control to the form. 3. In the Properties window, set the properties for the CheckedListBox control as follows: (Name): regioncheckedlistbox BackColor: White BorderStyle: FixedSingle Location: 12, 98 Size: 75, 62 Add items to the CheckedListBox control 1. On the form, right-click the CheckedListBox control, and then click Edit Items. 2. In the String Collection Editor dialog box, enter the items North, South, East, and West on separate lines, and then click OK. Create an enumeration that lists different regions 1. On the View menu, click Code. 2. In the MainForm class, create an enumeration called Regions that stores four regions.

Module 4: Data Types and Variables 4-51 3. Your code should resemble the following. // Creates an enumeration with four regions. enum Regions {North, South, East, West}; ' Creates an enumeration with four regions. Enum Regions North South East West End Enum Implement a button for the CheckedListBox control The following steps create a button on the form to display a message box with the regions currently selected. You will implement an array to store the regions selected. 1. On the View menu, click Designer. 2. In the Toolbox, in the Common Controls group, drag a Button control to the form. 3. In the Properties window, set the following properties for the button: (Name): regionbutton Location: 93, 97 Size: 75, 64 Text: Check Regions 4. Double-click the regionbutton button. This creates an event handler for the Click event of the button. 5. In the regionbutton_click event handler, create a string array that can contain all of the regions. 6. Set each element of the string array to the name of the corresponding region from the Regions enumeration, followed by a Boolean value that indicates whether the region is selected in the CheckedListBox control. You can obtain the Boolean value by using regioncheckedlistbox.getitemchecked(number), where number is the zero-based index of the item in the CheckedListBox control. 7. Display a message box that states which regions are selected. Your code should resemble the following. private void regionbutton_click(object sender, EventArgs e) { // Create a string array that can contain the four regions. string[]regionarray = new string[4]; // Set the elements to indicate whether each region is selected.

4-52 Module 4: Data Types and Variables } regionarray[0] = Regions.North + " = " + regioncheckedlistbox.getitemchecked(0); regionarray[1] = Regions.South + " = " + regioncheckedlistbox.getitemchecked(1); regionarray[2] = Regions.East + " = " + regioncheckedlistbox.getitemchecked(2); regionarray[3] = Regions.West + " = " + regioncheckedlistbox.getitemchecked(3); // Display the selected regions. MessageBox.Show("The following regions are selected:\n\n" + regionarray[0] + "\n" + regionarray[1] + "\n" + regionarray[2] + "\n" + regionarray[3], "Regions"); Private Sub regionbutton_click(byval sender As System.Object, ByVal e As _ System.EventArgs) Handles regionbutton.click ' Create a string array that can contain the four regions. Dim regionarray(3) As String ' Set the elements to indicate whether each region is selected. regionarray(0) = Regions.North.ToString() & " = " & _ regioncheckedlistbox.getitemchecked(0) regionarray(1) = Regions.South.ToString() & " = " & _ regioncheckedlistbox.getitemchecked(1) regionarray(2) = Regions.East.ToString() & " = " & _ regioncheckedlistbox.getitemchecked(2) regionarray(3) = Regions.West.ToString() & " = " & _ regioncheckedlistbox.getitemchecked(3) ' Display the selected regions. MessageBox.Show("The following regions are selected:" & vbcrlf & vbcrlf & _ regionarray(0) & vbcrlf & regionarray(1) & vbcrlf & regionarray(2) & _ vbcrlf & regionarray(3), "Regions") End Sub Build and test the application 1. On the Build menu, click Build Solution. Verify that the solution builds without any errors. 2. On the Debug menu, click Start Debugging. 3. In the User name text box, type your name. 4. In the Password text box, type your password, and then click OK. 5. In the message box, click OK. 6. On the application, click Check Regions. This displays a message box that states none of the regions are selected. 7. Click OK, select one or more regions, and then click Check Regions. This displays a message box that states the regions that are selected. 8. Click OK. Then close the application.

Module 4: Data Types and Variables 4-53 Results Checklist The following is a checklist of results for you to verify that you have performed this lab successfully. Ensure that you have performed the following tasks: Added a CheckedListBox control to the MainForm form. Added functionality to display the selected items. Lab Shutdown After you complete the lab, you must shut down the 4994A-LON-DEV-04 virtual machine and discard any changes. Important: If the Close dialog box appears, ensure that Turn off and delete changes is selected and then click OK.

4-54 Module 4: Data Types and Variables Lab Discussion Discuss the following questions: How can you reference a control on a form from another form? What is the scope of the user name and password variables? How can you modify the code that initializes the array to make it more efficient? How can you verify the selected items in a CheckedListBox control?