Module 4: Data Types and Variables
|
|
- Lionel Boone
- 6 years ago
- Views:
Transcription
1 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
2 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, addresses, logos, people, places, and events depicted herein are fictitious, and no association with any real company, organization, product, domain name, 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 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
3 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 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.
5 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.
6 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
7 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.
8 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.
9 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, /- 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 digits. Value Value Value decimal Decimal Monetary values 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
10 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
11 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.
12 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.
13 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.
14 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
15 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()
16 4-14 Module 4: Data Types and Variables Example The following example declares an integer variable called counter. int counter; Dim counter As Integer
17 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.
18 4-16 Module 4: Data Types and Variables Initializes, text strings to empty (""). Initializes date variables to January 1, 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
19 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.
20 4-18 Module 4: Data Types and Variables const double PI = ; int radius = 5; double area = PI * radius * radius; double circumference = 2 * PI * radius; Const PI As Double = Dim radius As Integer = 5 Dim area As Double = PI * radius * radius Dim circumference As Double = 2 * PI * radius
21 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.
22 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.
23 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
24 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
25 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
26 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.
27 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
28 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.
29 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 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, 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:
30 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;
31 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.
32 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.
33 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.
34 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.
35 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.
36 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-
37 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.
38 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.
39 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
40 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.
41 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")
42 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."
43 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.
44 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.
45 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
46 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
47 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.
48 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.
49 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.
50 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()
51 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.
52 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.
53 Module 4: Data Types and Variables 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.
54 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.
55 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.
56 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?
Module 6: Fundamentals of Object- Oriented Programming
Module 6: Fundamentals of Object- Oriented Programming Table of Contents Module Overview 6-1 Lesson 1: Introduction to Object-Oriented Programming 6-2 Lesson 2: Defining a Class 6-10 Lesson 3: Creating
More informationModule 9: Validating User Input
Module 9: Validating User Input Table of Contents Module Overview 9-1 Lesson 1: Restricting User Input 9-2 Lesson 2: Implementing Field-Level Validation 9-8 Lesson 3: Implementing Form-Level Validation
More informationUnit 4. Lesson 4.1. Managing Data. Data types. Introduction. Data type. Visual Basic 2008 Data types
Managing Data Unit 4 Managing Data Introduction Lesson 4.1 Data types We come across many types of information and data in our daily life. For example, we need to handle data such as name, address, money,
More informationModule 8: Building a Windows Forms User Interface
Module 8: Building a Windows Forms User Interface Table of Contents Module Overview 8-1 Lesson 1: Managing Forms and Dialog Boxes 8-2 Lesson 2: Creating Menus and Toolbars 8-13 Lab: Implementing Menus
More informationIntroduce C# as Object Oriented programming language. Explain, tokens,
Module 2 98 Assignment 1 Introduce C# as Object Oriented programming language. Explain, tokens, lexicals and control flow constructs. 99 The C# Family Tree C Platform Independence C++ Object Orientation
More informationLab Answer Key for Module 1: Creating Databases and Database Files
Lab Answer Key for Module 1: Creating Databases and Database Files Table of Contents Lab 1: Creating Databases and Database Files 1 Exercise 1: Creating a Database 1 Exercise 2: Creating Schemas 4 Exercise
More informationUka Tarsadia University MCA ( 3rd Semester)/M.Sc.(CA) (1st Semester) Course : / Visual Programming Question Bank
Unit 1 Introduction to.net Platform Q: 1 Answer in short. 1. Which three main components are available in.net framework? 2. List any two new features added in.net framework 4.0 which is not available in
More informationIT 374 C# and Applications/ IT695 C# Data Structures
IT 374 C# and Applications/ IT695 C# Data Structures Module 2.5: Methods A Deeper Look Xianrong (Shawn) Zheng Spring 2017 1 Outline static Methods, static Variables, and Class Math Methods with Multiple
More informationC#: framework overview and in-the-small features
Chair of Software Engineering Carlo A. Furia, Marco Piccioni, Bertrand Meyer C#: framework overview and in-the-small features Chair of Software Engineering Carlo A. Furia, Marco Piccioni, Bertrand Meyer
More information.Net Technologies. Components of.net Framework
.Net Technologies Components of.net Framework There are many articles are available in the web on this topic; I just want to add one more article over the web by explaining Components of.net Framework.
More informationLab Answer Key for Module 8: Implementing Stored Procedures
Lab Answer Key for Module 8: Implementing Stored Procedures Table of Contents Lab 8: Implementing Stored Procedures 1 Exercise 1: Creating Stored Procedures 1 Exercise 2: Working with Execution Plans 6
More informationAgenda & Reading. VB.NET Programming. Data Types. COMPSCI 280 S1 Applications Programming. Programming Fundamentals
Agenda & Reading COMPSCI 80 S Applications Programming Programming Fundamentals Data s Agenda: Data s Value s Reference s Constants Literals Enumerations Conversions Implicitly Explicitly Boxing and unboxing
More informationChapter 1 Getting Started
Chapter 1 Getting Started The C# class Just like all object oriented programming languages, C# supports the concept of a class. A class is a little like a data structure in that it aggregates different
More information2. 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
1. Which language is not a true object-oriented programming language? A. VB 6 B. VB.NET C. JAVA D. C++ 2. A GUI A. uses buttons, menus, and icons B. should be easy for a user to manipulate C. both (a)
More informationIntroduction To C#.NET
Introduction To C#.NET Microsoft.Net was formerly known as Next Generation Windows Services(NGWS).It is a completely new platform for developing the next generation of windows/web applications. However
More informationHierarchical inheritance: Contains one base class and multiple derived classes of the same base class.
1. What is C#? C# (pronounced "C sharp") is a simple, modern, object oriented, and type safe programming language. It will immediately be familiar to C and C++ programmers. C# combines the high productivity
More informationUNIT 1. Introduction to Microsoft.NET framework and Basics of VB.Net
UNIT 1 Introduction to Microsoft.NET framework and Basics of VB.Net 1 SYLLABUS 1.1 Overview of Microsoft.NET Framework 1.2 The.NET Framework components 1.3 The Common Language Runtime (CLR) Environment
More informationMicrosoft Visual Basic 2005: Reloaded
Microsoft Visual Basic 2005: Reloaded Second Edition Chapter 3 Variables, Constants, Methods, and Calculations Objectives After studying this chapter, you should be able to: Declare variables and named
More informationMicrosoft Visual Basic 2015: Reloaded
Microsoft Visual Basic 2015: Reloaded Sixth Edition Chapter Three Memory Locations and Calculations Objectives After studying this chapter, you should be able to: Declare variables and named constants
More informationCS201 - Introduction to Programming Glossary By
CS201 - Introduction to Programming Glossary By #include : The #include directive instructs the preprocessor to read and include a file into a source code file. The file name is typically enclosed with
More informationDarshan Institute of Engineering & Technology for Diploma Studies
Overview of Microsoft.Net Framework: The Dot Net or.net is a technology that is an outcome of Microsoft s new strategy to develop window based robust applications and rich web applications and to keep
More informationC#.Net. Course Contents. Course contents VT BizTalk. No exam, but laborations
, 1 C#.Net VT 2009 Course Contents C# 6 hp approx. BizTalk 1,5 hp approx. No exam, but laborations Course contents Architecture Visual Studio Syntax Classes Forms Class Libraries Inheritance Other C# essentials
More informationProgramming Language 2 (PL2)
Programming Language 2 (PL2) 337.1.1 - Explain rules for constructing various variable types of language 337.1.2 Identify the use of arithmetical and logical operators 337.1.3 Explain the rules of language
More informationVARIABLES. 1. STRINGS Data with letters and/or characters 2. INTEGERS Numbers without decimals 3. FLOATING POINT NUMBERS Numbers with decimals
VARIABLES WHAT IS A VARIABLE? A variable is a storage location in the computer s memory, used for holding information while the program is running. The information that is stored in a variable may change,
More informationShort Notes of CS201
#includes: Short Notes of CS201 The #include directive instructs the preprocessor to read and include a file into a source code file. The file name is typically enclosed with < and > if the file is a system
More informationIntroduction to Programming Using Java (98-388)
Introduction to Programming Using Java (98-388) Understand Java fundamentals Describe the use of main in a Java application Signature of main, why it is static; how to consume an instance of your own class;
More informationBASIC ELEMENTS OF A COMPUTER PROGRAM
BASIC ELEMENTS OF A COMPUTER PROGRAM CSC128 FUNDAMENTALS OF COMPUTER PROBLEM SOLVING LOGO Contents 1 Identifier 2 3 Rules for naming and declaring data variables Basic data types 4 Arithmetic operators
More informationQuestion And Answer.
Q.1 What would be the output of the following program? using System; namespaceifta classdatatypes static void Main(string[] args) inti; Console.WriteLine("i is not used inthis program!"); A. i is not used
More informationJava Primer 1: Types, Classes and Operators
Java Primer 1 3/18/14 Presentation for use with the textbook Data Structures and Algorithms in Java, 6th edition, by M. T. Goodrich, R. Tamassia, and M. H. Goldwasser, Wiley, 2014 Java Primer 1: Types,
More informationSKILL AREA 306: DEVELOP AND IMPLEMENT COMPUTER PROGRAMS
Add your company slogan SKILL AREA 306: DEVELOP AND IMPLEMENT COMPUTER PROGRAMS Computer Programming (YPG) LOGO 306.1 Review Selected Programming Environment 306.1.1 Explain the concept of reserve words,
More informationCS313D: ADVANCED PROGRAMMING LANGUAGE
CS313D: ADVANCED PROGRAMMING LANGUAGE Computer Science department Lecture 7 : Collections Lecture Contents 2 Why collections? What is a collection? Non-generic collections: Array & ArrayList Stack HashTable
More informationBit (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
* VB.NET Syntax I 1. Elements of code 2. Declaration and statements 3. Naming convention 4. Types and user defined types 5. Enumerations and variables Bit (0, 1) Byte (8 bits: 0-255) Numeral systems Binary
More informationContents. Figures. Tables. Examples. Foreword. Preface. 1 Basics of Java Programming 1. xix. xxi. xxiii. xxvii. xxix
PGJC4_JSE8_OCA.book Page ix Monday, June 20, 2016 2:31 PM Contents Figures Tables Examples Foreword Preface xix xxi xxiii xxvii xxix 1 Basics of Java Programming 1 1.1 Introduction 2 1.2 Classes 2 Declaring
More informationObjectives. Introduce the core C# language features class Main types variables basic input and output operators arrays control constructs comments
Basics Objectives Introduce the core C# language features class Main types variables basic input and output operators arrays control constructs comments 2 Class Keyword class used to define new type specify
More informationC# Fundamentals. Hans-Wolfgang Loidl School of Mathematical and Computer Sciences, Heriot-Watt University, Edinburgh
C# Fundamentals Hans-Wolfgang Loidl School of Mathematical and Computer Sciences, Heriot-Watt University, Edinburgh Semester 1 2018/19 H-W. Loidl (Heriot-Watt Univ) F20SC/F21SC 2018/19
More informationMicrosoft Exchange Server SMTPDiag
Microsoft Exchange Server SMTPDiag Contents Microsoft Exchange Server SMTPDiag...1 Contents... 2 Microsoft Exchange Server SMTPDiag...3 SMTPDiag Arguments...3 SMTPDiag Results...4 SMTPDiag Tests...5 Copyright...5
More informationHands-On Lab. Lab Manual HOL007 Understanding, Designing, and Refactoring Code Using the New Class Designer Tool in Microsoft Visual Studio 2005
Hands-On Lab Lab Manual HOL007 Understanding, Designing, and Refactoring Code Using the New Class Designer Tool in Microsoft Visual Studio 2005 Please do not remove this manual from the lab Page 1 Information
More informationObjectives. Describe ways to create constants const readonly enum
Constants Objectives Describe ways to create constants const readonly enum 2 Motivation Idea of constant is useful makes programs more readable allows more compile time error checking 3 Const Keyword const
More informationVba Variables Constant and Data types in Excel
Vba Variables Constant and Data types in Excel VARIABLES In Excel VBA, variables are areas allocated by the computer memory to hold data. Data stored inside the computer memory has 4 properties: names,
More informationC# Types. Industrial Programming. Value Types. Signed and Unsigned. Lecture 3: C# Fundamentals
C# Types Industrial Programming Lecture 3: C# Fundamentals Industrial Programming 1 Industrial Programming 2 Value Types Memory location contains the data. Integers: Signed: sbyte, int, short, long Unsigned:
More informationTokens, Expressions and Control Structures
3 Tokens, Expressions and Control Structures Tokens Keywords Identifiers Data types User-defined types Derived types Symbolic constants Declaration of variables Initialization Reference variables Type
More informationIndustrial Programming
Industrial Programming Lecture 3: C# Fundamentals Industrial Programming 1 C# Types Industrial Programming 2 Value Types Memory location contains the data. Integers: Signed: sbyte, int, short, long Unsigned:
More informationComputers and Programming Section 450. Lab #1 C# Basic. Student ID Name Signature
Lab #1 C# Basic Sheet s Owner Student ID Name Signature Group partner 1. Identifier Naming Rules in C# A name must consist of only letters (A Z,a z), digits (0 9), or underscores ( ) The first character
More informationPace University. Fundamental Concepts of CS121 1
Pace University Fundamental Concepts of CS121 1 Dr. Lixin Tao http://csis.pace.edu/~lixin Computer Science Department Pace University October 12, 2005 This document complements my tutorial Introduction
More informationChapter-8 DATA TYPES. Introduction. Variable:
Chapter-8 DATA TYPES Introduction To understand any programming languages we need to first understand the elementary concepts which form the building block of that program. The basic building blocks include
More informationHands-On Lab. Lab Manual HOLDEV083 Advanced Language Features in Visual Basic
Hands-On Lab Lab Manual HOLDEV083 Advanced Language Features in Visual Basic Please do not remove this manual from the lab The lab manual will be available from CommNet Release Date: May 2005 m Information
More informationObject-Oriented Programming
Object-Oriented Programming 1. What is object-oriented programming (OOP)? OOP is a technique to develop logical modules, such as classes that contain properties, methods, fields, and events. An object
More informationUnderstand Computer Storage and Data Types
Understand Computer Storage and Data Types Lesson Overview Students will understand computer storage and data types. In this lesson, you will learn: How a computer stores programs and instructions in computer
More informationCS313D: ADVANCED PROGRAMMING LANGUAGE
CS313D: ADVANCED PROGRAMMING LANGUAGE Computer Science department Lecture 8 : Collections Lecture Contents 2 Why collections? What is a collection? Non-generic collections: Array & ArrayList Stack HashTable
More informationModule 5: Programming with C#
Module 5: Programming with C# Contents Overview 1 Lesson: Using Arrays 2 Lesson: Using Collections 21 Lesson: Using Interfaces 35 Lesson: Using Exception Handling 55 Lesson: Using Delegates and Events
More informationObjectives. Chapter 2: Basic Elements of C++ Introduction. Objectives (cont d.) A C++ Program (cont d.) A C++ Program
Objectives Chapter 2: Basic Elements of C++ In this chapter, you will: Become familiar with functions, special symbols, and identifiers in C++ Explore simple data types Discover how a program evaluates
More informationChapter 2: Basic Elements of C++
Chapter 2: Basic Elements of C++ Objectives In this chapter, you will: Become familiar with functions, special symbols, and identifiers in C++ Explore simple data types Discover how a program evaluates
More informationChapter 2: Basic Elements of C++ Objectives. Objectives (cont d.) A C++ Program. Introduction
Chapter 2: Basic Elements of C++ C++ Programming: From Problem Analysis to Program Design, Fifth Edition 1 Objectives In this chapter, you will: Become familiar with functions, special symbols, and identifiers
More informationLesson 06 Arrays. MIT 11053, Fundamentals of Programming By: S. Sabraz Nawaz Senior Lecturer in MIT Department of MIT FMC, SEUSL
Lesson 06 Arrays MIT 11053, Fundamentals of Programming By: S. Sabraz Nawaz Senior Lecturer in MIT Department of MIT FMC, SEUSL Array An array is a group of variables (called elements or components) containing
More informationCSC Web Programming. Introduction to JavaScript
CSC 242 - Web Programming Introduction to JavaScript JavaScript JavaScript is a client-side scripting language the code is executed by the web browser JavaScript is an embedded language it relies on its
More informationJava How to Program, 10/e. Copyright by Pearson Education, Inc. All Rights Reserved.
Java How to Program, 10/e Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved. Data structures Collections of related data items. Discussed in depth in Chapters 16 21. Array objects Data
More informationCHAPTER 7 OBJECTS AND CLASSES
CHAPTER 7 OBJECTS AND CLASSES OBJECTIVES After completing Objects and Classes, you will be able to: Explain the use of classes in Java for representing structured data. Distinguish between objects and
More information2007 MICROSOFT OFFICE SYSTEM USER INTERFACE DESIGN GUIDELINES PREVIEW
2007 MICROSOFT OFFICE SYSTEM USER INTERFACE DESIGN GUIDELINES PREVIEW Preview of the Guidelines for Licensing the 2007 Microsoft Office System User Interface 2006 Microsoft Corporation. All rights reserved.
More informationModule 7: Automating Administrative Tasks
Module 7: Automating Administrative Tasks Table of Contents Module Overview 7-1 Lesson 1: Automating Administrative Tasks in SQL Server 2005 7-2 Lesson 2: Configuring SQL Server Agent 7-10 Lesson 3: Creating
More informationC++\CLI. Jim Fawcett CSE687-OnLine Object Oriented Design Summer 2017
C++\CLI Jim Fawcett CSE687-OnLine Object Oriented Design Summer 2017 Comparison of Object Models Standard C++ Object Model All objects share a rich memory model: Static, stack, and heap Rich object life-time
More informationData Types, Variables and Arrays. OOC 4 th Sem, B Div Prof. Mouna M. Naravani
Data Types, Variables and Arrays OOC 4 th Sem, B Div 2016-17 Prof. Mouna M. Naravani Identifiers in Java Identifiers are the names of variables, methods, classes, packages and interfaces. Identifiers must
More informationModule 2: Introduction to a Managed Execution Environment
Module 2: Introduction to a Managed Execution Environment Contents Overview 1 Writing a.net Application 2 Compiling and Running a.net Application 11 Lab 2: Building a Simple.NET Application 29 Review 32
More informationUNIT- 3 Introduction to C++
UNIT- 3 Introduction to C++ C++ Character Sets: Letters A-Z, a-z Digits 0-9 Special Symbols Space + - * / ^ \ ( ) [ ] =!= . $, ; : %! &? _ # = @ White Spaces Blank spaces, horizontal tab, carriage
More informationCS313D: ADVANCED PROGRAMMING LANGUAGE
CS313D: ADVANCED PROGRAMMING LANGUAGE Computer Science department Lecture 8 : Collections Lecture Contents 2 Why collections? What is a collection? Non-generic collections: Array & ArrayList Stack HashTable
More informationChapter 6 Introduction to Defining Classes
Introduction to Defining Classes Fundamentals of Java: AP Computer Science Essentials, 4th Edition 1 Objectives Design and implement a simple class from user requirements. Organize a program in terms of
More informationIndex. object lifetimes, and ownership, use after change by an alias errors, use after drop errors, BTreeMap, 309
A Arithmetic operation floating-point arithmetic, 11 12 integer numbers, 9 11 Arrays, 97 copying, 59 60 creation, 48 elements, 48 empty arrays and vectors, 57 58 executable program, 49 expressions, 48
More informationAbsolute C++ Walter Savitch
Absolute C++ sixth edition Walter Savitch Global edition This page intentionally left blank Absolute C++, Global Edition Cover Title Page Copyright Page Preface Acknowledgments Brief Contents Contents
More informationCE221 Programming in C++ Part 1 Introduction
CE221 Programming in C++ Part 1 Introduction 06/10/2017 CE221 Part 1 1 Module Schedule There are two lectures (Monday 13.00-13.50 and Tuesday 11.00-11.50) each week in the autumn term, and a 2-hour lab
More informationDuhok Polytechnic University Amedi Technical Institute/ IT Dept. Halkawt Rajab Hussain
Duhok Polytechnic University Amedi Technical Institute/ IT Dept. By Halkawt Rajab Hussain 2016-04-02 Overview. C# program structure. Variables and Constant. Conditional statement (if, if/else, nested if
More informationPROGRAMMING IN VISUAL BASIC WITH MICROSOFT VISUAL STUDIO Course: 10550A; Duration: 5 Days; Instructor-led
CENTER OF KNOWLEDGE, PATH TO SUCCESS Website: PROGRAMMING IN VISUAL BASIC WITH MICROSOFT VISUAL STUDIO 2010 Course: 10550A; Duration: 5 Days; Instructor-led WHAT YOU WILL LEARN This course teaches you
More informationModule 3: Managing Groups
Module 3: Managing Groups Contents Overview 1 Lesson: Creating Groups 2 Lesson: Managing Group Membership 20 Lesson: Strategies for Using Groups 27 Lesson: Using Default Groups 44 Lab: Creating and Managing
More informationMicrosoft Dynamics GP Release Integration Guide For Microsoft Retail Management System Headquarters
Microsoft Dynamics GP Release 10.0 Integration Guide For Microsoft Retail Management System Headquarters Copyright Copyright 2007 Microsoft Corporation. All rights reserved. Complying with all applicable
More informationObject-Oriented Programming in C# (VS 2015)
Object-Oriented Programming in C# (VS 2015) This thorough and comprehensive 5-day course is a practical introduction to programming in C#, utilizing the services provided by.net. This course emphasizes
More informationMicrosoft. Microsoft Visual C# Step by Step. John Sharp
Microsoft Microsoft Visual C#- 2010 Step by Step John Sharp Table of Contents Acknowledgments Introduction xvii xix Part I Introducing Microsoft Visual C# and Microsoft Visual Studio 2010 1 Welcome to
More informationCS 231 Data Structures and Algorithms, Fall 2016
CS 231 Data Structures and Algorithms, Fall 2016 Dr. Bruce A. Maxwell Department of Computer Science Colby College Course Description Focuses on the common structures used to store data and the standard
More informationThis tutorial has been prepared for the beginners to help them understand basics of c# Programming.
About thetutorial C# is a simple, modern, general-purpose, object-oriented programming language developed by Microsoft within its.net initiative led by Anders Hejlsberg. This tutorial covers basic C# programming
More informationGetting started 7. Storing values 21. Creating variables 22 Reading input 24 Employing arrays 26 Casting data types 28 Fixing constants 30 Summary 32
Contents 1 2 3 Contents Getting started 7 Introducing C# 8 Installing Visual Studio 10 Exploring the IDE 12 Starting a Console project 14 Writing your first program 16 Following the rules 18 Summary 20
More informationVisual C# Instructor s Manual Table of Contents
Visual C# 2005 2-1 Chapter 2 Using Data At a Glance Instructor s Manual Table of Contents Overview Objectives s Quick Quizzes Class Discussion Topics Additional Projects Additional Resources Key Terms
More informationObject-Oriented Programming in C# (VS 2012)
Object-Oriented Programming in C# (VS 2012) This thorough and comprehensive course is a practical introduction to programming in C#, utilizing the services provided by.net. This course emphasizes the C#
More informationControl Flow. COMS W1007 Introduction to Computer Science. Christopher Conway 3 June 2003
Control Flow COMS W1007 Introduction to Computer Science Christopher Conway 3 June 2003 Overflow from Last Time: Why Types? Assembly code is typeless. You can take any 32 bits in memory, say this is an
More informationC# Programming in the.net Framework
50150B - Version: 2.1 04 May 2018 C# Programming in the.net Framework C# Programming in the.net Framework 50150B - Version: 2.1 6 days Course Description: This six-day instructor-led course provides students
More informationExercise: Using Numbers
Exercise: Using Numbers Problem: You are a spy going into an evil party to find the super-secret code phrase (made up of letters and spaces), which you will immediately send via text message to your team
More informationVISUAL BASIC 2005 EXPRESS: NOW PLAYING
VISUAL BASIC 2005 EXPRESS: NOW PLAYING by Wallace Wang San Francisco ADVANCED DATA STRUCTURES: QUEUES, STACKS, AND HASH TABLES Using a Queue To provide greater flexibility in storing information, Visual
More informationDigiPen Institute of Technology
DigiPen Institute of Technology Presents Session Two: Overview of C# Programming DigiPen Institute of Technology 5001 150th Ave NE, Redmond, WA 98052 Phone: (425) 558-0299 www.digipen.edu 2005 DigiPen
More informationJava How to Program, 10/e. Copyright by Pearson Education, Inc. All Rights Reserved.
Java How to Program, 10/e Education, Inc. All Rights Reserved. Each class you create becomes a new type that can be used to declare variables and create objects. You can declare new classes as needed;
More informationAppendix G: Writing Managed C++ Code for the.net Framework
Appendix G: Writing Managed C++ Code for the.net Framework What Is.NET?.NET is a powerful object-oriented computing platform designed by Microsoft. In addition to providing traditional software development
More informationPART I. Part II Answer to all the questions 1. What is meant by a token? Name the token available in C++.
Unit - III CHAPTER - 9 INTRODUCTION TO C++ Choose the correct answer. PART I 1. Who developed C++? (a) Charles Babbage (b) Bjarne Stroustrup (c) Bill Gates (d) Sundar Pichai 2. What was the original name
More informationIntroduction to Data Entry and Data Types
212 Chapter 4 Variables and Arithmetic Operations STEP 1 With the Toolbox visible (see Figure 4-21), click the Toolbox Close button. The Toolbox closes and the work area expands in size.to reshow the Toolbox
More informationProcedures in Visual Basic
Procedures in Visual Basic https://msdn.microsoft.com/en-us/library/y6yz79c3(d=printer).aspx 1 of 3 02.09.2016 18:50 Procedures in Visual Basic Visual Studio 2015 A procedure is a block of Visual Basic
More informationExcel VBA Variables, Data Types & Constant
Excel VBA Variables, Data Types & Constant Variables are used in almost all computer program and VBA is no different. It's a good practice to declare a variable at the beginning of the procedure. It is
More informationIntroduction Primitive Data Types Character String Types User-Defined Ordinal Types Array Types. Record Types. Pointer and Reference Types
Chapter 6 Topics WEEK E FOUR Data Types Introduction Primitive Data Types Character String Types User-Defined Ordinal Types Array Types Associative Arrays Record Types Union Types Pointer and Reference
More informationProgramming for the Web with PHP
Aptech Ltd Version 1.0 Page 1 of 11 Table of Contents Aptech Ltd Version 1.0 Page 2 of 11 Abstraction Anonymous Class Apache Arithmetic Operators Array Array Identifier arsort Function Assignment Operators
More informationChapter 2 Basic Elements of C++
C++ Programming: From Problem Analysis to Program Design, Fifth Edition 2-1 Chapter 2 Basic Elements of C++ At a Glance Instructor s Manual Table of Contents Overview Objectives s Quick Quizzes Class Discussion
More informationCourse Hours
Programming the.net Framework 4.0/4.5 with C# 5.0 Course 70240 40 Hours Microsoft's.NET Framework presents developers with unprecedented opportunities. From 'geoscalable' web applications to desktop and
More informationCOPYRIGHTED MATERIAL. Contents. Part I: C# Fundamentals 1. Chapter 1: The.NET Framework 3. Chapter 2: Getting Started with Visual Studio
Introduction XXV Part I: C# Fundamentals 1 Chapter 1: The.NET Framework 3 What s the.net Framework? 3 Common Language Runtime 3.NET Framework Class Library 4 Assemblies and the Microsoft Intermediate Language
More informationIntroduction to.net, C#, and Visual Studio. Part I. Administrivia. Administrivia. Course Structure. Final Project. Part II. What is.net?
Introduction to.net, C#, and Visual Studio C# Programming Part I Administrivia January 8 Administrivia Course Structure When: Wednesdays 10 11am (and a few Mondays as needed) Where: Moore 100B This lab
More informationChapter 2. Building Multitier Programs with Classes The McGraw-Hill Companies, Inc. All rights reserved. McGraw-Hill
Chapter 2 Building Multitier Programs with Classes McGraw-Hill 2010 The McGraw-Hill Companies, Inc. All rights reserved. Objectives Discuss object-oriented terminology Create your own class and instantiate
More informationLesson 02 Working with Data Types. MIT 31043: VISUAL PROGRAMMING By: S. Sabraz Nawaz Senior Lecturer in MIT
Lesson 02 Working with Data Types MIT 31043: VISUAL PROGRAMMING Senior Lecturer in MIT Variables A variable is a storage location in memory that is represented by a name. A variable stores data, which
More informationFig 1.1.NET Framework Architecture Block Diagram
Overview of Microsoft.NET Framework The.NET Framework is a technology that supports building and running the next generation of applications and XML Web services. Using.Net technology it is easy to use
More informationDefinition: Data Type A data type is a collection of values and the definition of one or more operations on those values.
Data Types 1 Definition: Data Type A data type is a collection of values and the definition of one or more operations on those values. Base Data Types All the values of the type are ordered and atomic.
More information