Object-Oriented Programming in Visual Basic

Size: px
Start display at page:

Download "Object-Oriented Programming in Visual Basic"

Transcription

1 Object-Oriented Programming in Visual Basic Student Guide Revision 4.0 Object Innovations Course 4201

2 Object-Oriented Programming in Visual Basic Rev. 4.0 Student Guide Information in this document is subject to change without notice. Companies, names and data used in examples herein are fictitious unless otherwise noted. No part of this document may be reproduced or transmitted in any form or by any means, electronic or mechanical, for any purpose, without the express written permission of Object Innovations. Product and company names mentioned herein are the trademarks or registered trademarks of their respective owners. is a registered trademark of Object Innovations. Authors: Robert J. Oberg and Dana Wyatt Special Thanks: Ernani Cecon, Jr. Copyright 2010 Object Innovations Enterprises, LLC All rights reserved.. Object Innovations Printed in the United States of America. Rev. 4.0 Copyright 2010 Object Innovations Enterprises, LLC ii

3 Table of Contents (Overview) Chapter 1.NET: What You Need to Know Chapter 2 Fundamentals of Visual Basic Programming Chapter 3 Control Structures Chapter 4 Procedures Chapter 5 Advanced Data Types Chapter 6 Exception Handling Chapter 7 Object-Oriented Programming Chapter 8 Inheritance Chapter 9 Interfaces and Collections Chapter 10 Introduction to Windows Forms Chapter 11 Windows Forms Controls Chapter 12 User Interface Features Chapter 13 Database Programming Chapter 14 Newer Features in Visual Basic Appendix A Using Visual Studio 2010 Appendix B Learning Resources Rev. 4.0 Copyright 2010 Object Innovations Enterprises, LLC iii

4 Directory Structure The course software installs to the root directory C:\OIC\IntroVb. Example programs for each chapter are in named subdirectories of chapter directories Chap01, Chap02, and so on. The Labs directory contains one subdirectory for each lab, named after the lab number. Starter code is frequently supplied, and answers are provided in the chapter directories. The CaseStudy directory contains a case study in multiple steps. The Demos directory is provided for performing in-class demonstrations led by the instructor. Data files install to the directory C:\OIC\Data. Rev. 4.0 Copyright 2010 Object Innovations Enterprises, LLC iv

5 Table of Contents (Detailed) Chapter 1.NET: What You Need to Know... 1 Getting Started... 3.NET: What Is Really Happening... 4.NET Programming in a Nutshell... 5.NET Program Example... 6 Viewing the Assembly... 7 Viewing Intermediate Language... 8 Understanding.NET... 9 Creating a Console Application Visual Studio Solutions Starter Code Using the Visual Studio Text Editor IntelliSense Build and Run the Project Pausing the Output Visual Basic and GUI Programs NET Documentation Summary Chapter 2 Fundamentals of Visual Basic Programming Visual Basic Hello, World Compiling, Running (Command Line) Program Structure Namespaces Project Imports Startup Object Naming Standards Keywords Multiple-File Program Structure Using Procedures Data Types IEEE 754 Floating Point Standard Data Type Ranges Literals Variables Initialization of Variables Type Checking Weak Type Checking Example Constants Data Conversions Operators and Expressions Arithmetic Operators Rev. 4.0 Copyright 2010 Object Innovations Enterprises, LLC v

6 String Operators Relational Operators Logical Operators Bitwise Operators Assignment Operators Operator Precedence Console I/O Console Input Console Output Placeholders A Practical Example Implicit Line Continuation Lab Summary Chapter 3 Control Structures Control Structures If/Then Statement If/Then/Else Statement Payroll Example Select Case Statement Lab 3A Looping Do/Loop Statement Leap Year Example Exiting Do Loops Prematurely While Statement For/Next Statement A Random Number Example Lab 3B Continue Statement Summary Chapter 4 Procedures Modules Subroutines ByVal Parameters ByRef Parameters Functions A Game Example Access, Modules, and Scope Scope Scope Example Part Scope Example Part Scope Example Part Shared Variables Overloading Optional Parameters Rev. 4.0 Copyright 2010 Object Innovations Enterprises, LLC vi

7 Variable Length Parameter Lists Lab 4A Lab 4B Summary Chapter 5 Advanced Data Types Arrays Initializing Arrays Using UBound An Example Using Arrays Multi-Dimensional Arrays Arrays are a Reference Type Reference Assignment Issues Jagged Arrays An Example Using Jagged Arrays Dynamic Arrays Releasing Memory for the Array System.Array System.Array Functions Lab 5A Enumerations System.Enum System.Enum Functions Structures With Statement Structure Assignment An Example Using Structures Lab 5B Pass-by-Value versus Pass-by-Reference Value Types vs. Reference Types Using ByVal with Value Types Using ByRef with Value Types Using ByVal with Reference Types Summary Chapter 6 Exception Handling Handling Errors Visual Basic Exception Handling Exception Message Demo System.Exception Exception Flow of Control Handling Multiple Exceptions Throwing Exceptions Types of Exceptions Context and Stack Unwinding Exception Handling Strategies Fahrenheit/Celsius Version Fahrenheit/Celsius Version Rev. 4.0 Copyright 2010 Object Innovations Enterprises, LLC vii

8 Fahrenheit/Celsius Version Fahrenheit/Celsius Version Inner Exceptions Custom Exceptions Lab Summary Chapter 7 Object-Oriented Programming Object-Oriented Programming Objects in Software Abstraction and Encapsulation Classes Creating a Class Defining Data Members Defining Methods Creating Objects Using Objects Assigning Object References Garbage Collection Me Properties Defining Properties ReadOnly Properties WriteOnly Properties Auto-Implemented Properties Auto-Implemented Property Example Shared Attributes Shared Methods and Properties An Arithmetic Calculator Example Constructors and Initialization Defining Constructors Default Constructor Shared Constructor Constructor Examples ReadOnly Members Constant Members Events Defining Events Restrictions on Event Procedures Raising Events Trapping Events Using WithEvents Trapping Events Dynamically A Banking Example ToString in User-Defined Classes Operator Overloading Lab Summary Rev. 4.0 Copyright 2010 Object Innovations Enterprises, LLC viii

9 Chapter 8 Inheritance Inheritance Inheritance Hierarchy Defining a Derived Class A Simple Example: Types of People NET s Object Class Controlling Base Class Construction Derived Class Construction Derived Class Constructors Need For Protected Access Modifier Access Control Using Protected Access Exceptions Defining Custom Exceptions Using Custom Exceptions Shadowing Base Class Methods Polymorphism Defining a Method as Overridable Overriding a Method Using Heterogeneous Collections with Polymorphic Methods Abstract Classes Not Inheritable Classes Type Conversions in Inheritance CType Lab Summary Chapter 9 Interfaces and Collections Components and OO in Visual Basic Interfaces Interfaces in Visual Basic Implementing an Interface Using an Interface Multiple Interfaces Using Multiple Interfaces TypeOf... Is and Dynamic Interfaces Interfaces in Visual Basic and COM Resolving Ambiguity in Interfaces NET Interfaces Arrays of User-Defined Objects Implementing IComparable Lab 9A Collections ArrayList ArrayList Methods Example: StringList IEnumerable and IEnumerator Rev. 4.0 Copyright 2010 Object Innovations Enterprises, LLC ix

10 Using Enumerators Collections of User-Defined Objects Account Class Collection Interfaces ICollection IList Default Properties Using the Item Property Lab 9B Writing Generic Code Using a Class of Object Generic Types Generic Example Generic Client Code System.Collections.Generic Lab 9C Summary Chapter 10 Introduction to Windows Forms Windows Forms Creating a Windows Forms App Aligning Controls Setting the Tab Order Partial Classes Windows Forms Event Handling Add Events for a Control Events Documentation Closing a Form ListBox Control ListBox Example My Command Line Arguments Lab Summary Chapter 11 Windows Forms Controls Common Properties Common Events Event Handling Sample Controls Using a Label Using Mnemonics Using a Text Box Using a Button Lab 11A Using a Radio Button and Group Box Using a Check Box Using the ToolTip Control Rev. 4.0 Copyright 2010 Object Innovations Enterprises, LLC x

11 Lab 11B Using a ListBox Control Adding ListBox Items Removing ListBox Items Selecting an Item in a List Box Using a ComboBox Control Flexible Events Handlers Timer Control Lab 11C Summary Chapter 12 User Interface Features Dialog Boxes MessageBox Custom Dialogs Adding a Custom Dialog Using DialogResult Displaying a Dialog Tab Order and Focus Initializing a Custom Dialog Changing the Behavior of a Button s DialogResult Lab 12A Modeless Dialogs Managing the Relationship between Forms Programming the Apply and Close Buttons Enabling / Disabling the Apply Button Common Dialogs Using a Common Dialog Control Menus MenuStrip Control A Calculator Example Application Calculator Starter Code Attaching a Menu to a Form Configuring Items in a Menu Testing the Menu Responding to Menu Events Changing Menu Item Appearance Modified SetOperation() Method ContextMenuStrip Control Example: Integrating a Context Menu into an Application Context Menu Events Handling Multiple Events Lab 12B Summary Chapter 13 Database Programming ADO.NET ADO.NET Architecture Rev. 4.0 Copyright 2010 Object Innovations Enterprises, LLC xi

12 .NET Data Providers Programming with ADO.NET Interfaces NET Namespaces Connected Data Access Sample Database Example: Connecting to SQL Server ADO.NET Class Libraries Connecting to an OLE DB Data Provider Importing a Namespace Using Commands Creating a Command Object ExecuteNonQuery Using a Data Reader Data Reader: Code Example Lab 13A Disconnected Datasets Data Adapters Data Bound Controls DataGridView Control DataGridView Sample Program DataGridView Demo Performing a Query Lab 13B Summary Chapter 14 Newer Features in Visual Basic Local Type Inference Local Type Inference Example Object Initializers Array Initializers Anonymous Types Partial Methods Partial Method Definition Partial Method Implementation Test Program Running the Example Extension Methods Extension Methods Example Collection Initializers Variance in Generic Interfaces Covariance Example Variance with IComparer(Of T) Language-Integrated Query (LINQ) LINQ Example Using IEnumerable(OfT> Summary Rev. 4.0 Copyright 2010 Object Innovations Enterprises, LLC xii

13 Appendix A Using Visual Studio A Visual Studio Solution Toolbars Customizing a Toolbar Creating a Console Application Using the Visual Studio Text Editor Build and Run the Bytes Project Running the Bytes Project Executable File Location Managing Configurations Project Configurations Debugging Just-in-Time Debugging Demo Breakpoints Watch Variables Debug Toolbar Stepping with the Debugger Demo: Stepping with the Debugger Call Stack Multiple-Project Solution Demo Adding a Reference Project Dependencies Startup Project Hidden Files Summary Appendix B Learning Resources Rev. 4.0 Copyright 2010 Object Innovations Enterprises, LLC xiii

14 Rev. 4.0 Copyright 2010 Object Innovations Enterprises, LLC xiv

15 IntroVb Chapter 1 Chapter 1.NET: What You Need to Know Rev.4.0 Copyright 2010 Object Innovations Enterprises, LLC 1

16 IntroVb Chapter 1.NET: What You Need to Know Objectives After completing this unit you will be able to: Describe the essentials of creating and running a program in the.net environment. Build and run a simple Visual Basic program in the.net environment. Use the ILDASM tool to view intermediate language. Use Visual Studio 2010 as an effective environment for creating Visual Basic programs. Use the.net Framework SDK documentation. Rev.4.0 Copyright 2010 Object Innovations Enterprises, LLC 2

17 IntroVb Chapter 1 Getting Started From a programmer s perspective, a beautiful thing about.net is that you scarcely need to know anything about it to start writing programs for the.net environment. You write a program in a high-level language (such as Visual Basic), a compiler creates an executable.exe file (called an assembly), and you run that.exe file. Even very simple programs, if they are designed to do something interesting, such as perform output, will require that the program employ the services of library code. A large library, called the.net Framework Class Library, comes with.net, and you can use all of the services of this library in your programs. Rev.4.0 Copyright 2010 Object Innovations Enterprises, LLC 3

18 IntroVb Chapter 1.NET: What Is Really Happening The assembly that is created does not contain executable code, but, rather, code in Intermediate Language, or IL (sometimes called Microsoft Intermediate Language, or MSIL). In the Windows environment, this IL code is packaged up in a standard portable executable (PE) file format, so you will see the familiar.exe extension (or, if you are building a component, the.dll extension). You can view an assembly using the ILDASM tool. When you run the.exe, a special runtime environment (the Common Language Runtime, or CLR) is launched and the IL instructions are executed by the CLR. Unlike some runtimes, where the IL would be interpreted each time it is executed, the CLR comes with a just-in-time (JIT) compiler, which translates the IL to native machine code the first time it is encountered. On subsequent calls, the code segment runs as native code. Rev.4.0 Copyright 2010 Object Innovations Enterprises, LLC 4

19 IntroVb Chapter 1.NET Programming in a Nutshell 1. Write your program in a high-level.net language, such as Visual Basic. 2. Compile your program into IL. 3. Run your IL program, which will launch the CLR to execute your IL, using its JIT to translate your program to native code as it executes. We will look at a simple example of a Visual Basic program, and run it under.net. Don t worry about the syntax of Visual Basic, which we will start discussing in the next chapter. Rev.4.0 Copyright 2010 Object Innovations Enterprises, LLC 5

20 IntroVb Chapter 1.NET Program Example See SimpleCalc in the Chap01 folder. 1. Enter the program in a text editor. ' SimpleCalc.vb ' ' This program does a simple calculation: calculate ' area of a rectangle Module SimpleCalc Sub Main () Dim base As Integer = 20 Dim height As Integer = 5 Dim area As Integer area = base * height System.Console.WriteLine("Area = {0}", area) End Sub End Module 2. Compile the program at the command line. Start the console window via Start All Programs Microsoft Visual Studio 2010 Visual Studio Tools Visual Studio Command Prompt (2010). Navigate to the Chap01\SimpleCalc folder. >vbc SimpleCalc.vb 3. Run your IL program SimpleCalc.exe >SimpleCalc area = 100 Rev.4.0 Copyright 2010 Object Innovations Enterprises, LLC 6

21 IntroVb Chapter 1 Viewing the Assembly You can view the assembly using the ILDASM tool. >ildasm SimpleCalc.exe Rev.4.0 Copyright 2010 Object Innovations Enterprises, LLC 7

22 IntroVb Chapter 1 Viewing Intermediate Language Double-click on Main:void() Rev.4.0 Copyright 2010 Object Innovations Enterprises, LLC 8

23 IntroVb Chapter 1 Understanding.NET The nice thing about a high-level programming language is that you usually do not need to be concerned with the platform on which the program executes. You can work with the abstractions provided by the language and with functions provided by libraries. Your appreciation of the Visual Basic programming language and its potential for creating great applications will be richer if you have a general understanding of.net. After this course, we suggest you next study:.net Framework Using Visual Basic After that there are many courses, such as: Windows Presentation Foundation Using Visual Basic ASP.NET Using Visual Basic Silverlight 4 Using Visual Basic Rev.4.0 Copyright 2010 Object Innovations Enterprises, LLC 9

24 IntroVb Chapter 1 Creating a Console Application We will now create a simple console application. Our program is the same simple calculator we created earlier that was compiled at the command line. 1. From the Visual Studio main menu, choose File New Project... This will bring up the New Project dialog. 2. Choose Console Application. 3. In the Name field, type SimpleCalcVs and for Location browse to C:\OIC\IntroVb\Demos. Click OK. Rev.4.0 Copyright 2010 Object Innovations Enterprises, LLC 10

25 IntroVb Chapter 1 Visual Studio Solutions In Visual Studio 2010, project information is organized by solutions and projects. A solution, specified by a.sln file, consists of one or more projects, specified by.vbproj files in the case of Visual Basic. Notice Solution Explorer in the top-right. Rev.4.0 Copyright 2010 Object Innovations Enterprises, LLC 11

26 IntroVb Chapter 1 Starter Code We see that a Visual Studio solution has been created with one project. The project contains two elements. The folder MyProject contains a number of files that we normally will not need to touch. Module1.vb contains skeleton code that we will edit. We ve closed a few windows that we don t need at this point. Rev.4.0 Copyright 2010 Object Innovations Enterprises, LLC 12

27 IntroVb Chapter 1 Using the Visual Studio Text Editor In Solution Explorer, change the name of the file Module1.vb to SimpleCalc.vb. Other changes will be made for you automatically, such as changing the name of the module to SimpleCalc. Make the following edits, using the Visual Studio text editor. Module SimpleCalc Sub Main() Dim base As Integer = 20 Dim height As Integer = 5 Dim area As Integer area = base * height System.Console.WriteLine("Area = {0}", area) End Sub End Module Notice that the Visual Studio text editor highlights syntax, indents automatically, and so on. In Visual Basic, as opposed to Visual C#, the editor does other things for you too, such as supply matching End keywords, adjust capitalization of keywords, and so on. Rev.4.0 Copyright 2010 Object Innovations Enterprises, LLC 13

28 IntroVb Chapter 1 IntelliSense A powerful feature of Visual Studio is IntelliSense. IntelliSense will automatically pop up a list box allowing you to easily insert language elements directly into your code. Rev.4.0 Copyright 2010 Object Innovations Enterprises, LLC 14

29 IntroVb Chapter 1 Build and Run the Project Building a project means compiling the individual source files and linking them together with any library files to create an IL executable.exe file. You can build the project by using one of the following: Menu Build Build Solution or toolbar button shortcut Ctrl+Shift+B. or keyboard Menu Build Build SimpleCalcVs or toolbar button just builds the project SimpleCalcVs) 1. (this You can run the program without the debugger by using one of the following: Toolbar (This toolbar button is not provided by default; see Appendix A for how to add it to your Build toolbar.) Keyboard shortcut Ctrl + F5 You can run the program in the debugger by using one of the following: Menu Debug Start Debugging Toolbar Keyboard shortcut F5 Try it! 1 The two are the same in this case, because the solution has only one project, but some solutions have multiple projects, and then there is a difference. Rev.4.0 Copyright 2010 Object Innovations Enterprises, LLC 15

30 IntroVb Chapter 1 Pausing the Output If you run the program in the debugger from Visual Studio, you will notice that the output window automatically closes on program termination. To keep the window open, you may prompt the user for some input. Module SimpleCalc Sub Main() Dim base As Integer = 20 Dim height As Integer = 5 Dim area As Integer area = base * height System.Console.WriteLine("Area = {0}", area) System.Console.WriteLine( _ "Prese Enter to exit") System.Console.ReadLine() End Sub End Module This version of the program is saved as a Visual Studio 2010 project in Chap01\SimpleCalcVs. Remember that you can always make the console window stay open by running without the debugger via Control + F5. Rev.4.0 Copyright 2010 Object Innovations Enterprises, LLC 16

31 IntroVb Chapter 1 Visual Basic and GUI Programs Microsoft s Visual Basic language works very effectively in a GUI environment. Using Windows Forms, it is easy to create Windows GUI programs in Visual Basic. Example: See Chap01\SimpleCalcGui We will discuss GUI programming using Visual Basic in Chapter 6. Rev.4.0 Copyright 2010 Object Innovations Enterprises, LLC 17

32 IntroVb Chapter 1.NET Documentation MSDN documentation for the.net Framework is included with Visual Studio Use the menu Help View Help. You may also find the documentation on the Web: Rev.4.0 Copyright 2010 Object Innovations Enterprises, LLC 18

33 IntroVb Chapter 1 Summary As in other environments, with.net you write a program in a high-level language, compile to an executable (.EXE file), and run that.exe file. The.EXE file, called an assembly, contains Intermediate Language instructions. You can view an assembly through the ILDASM tool. Visual Studio 2010 is a powerful IDE that makes it easy to develop Visual Basic programs. With Visual Studio, it is easy to create GUI programs using Visual Basic. You can access extensive.net Framework documentation through the Visual Studio help system. Rev.4.0 Copyright 2010 Object Innovations Enterprises, LLC 19

34 IntroVb Chapter 1 Rev.4.0 Copyright 2010 Object Innovations Enterprises, LLC 20

35 IntroVb Chapter 2 Chapter 2 Fundamentals of Visual Basic Programming Rev. 4.0 Copyright 2010 Object Innovations Enterprises, LLC 21

36 IntroVb Chapter 2 Fundamentals of Visual Basic Programming Objectives After completing this unit you will be able to: Build and run Visual Basic programs. Describe the basic structure of Visual Basic programs. Describe the use of namespaces in Visual Basic. Describe data types available in Visual Basic. Perform calculations in Visual Basic. Use console I/O in Visual Basic console programs. Rev. 4.0 Copyright 2010 Object Innovations Enterprises, LLC 22

37 IntroVb Chapter 2 Visual Basic Visual Basic is a powerful, flexible programming language. It supports a variety of data types, operators and control structures. It can be used to create user-defined classes and it supports inheritance. It supports structured exception handling. It can be used to create threads. In order to take full advantage of the.net Framework, Visual Basic makes some significant changes to the VB6 programming model. This will present some challenges to VB6 programmers, but migration tools should assist in the process. As a terminology note, beginning with.net 2.0, Microsoft has dropped the.net in the Visual Basic language. The pre-.net version of the language is now referred to as Visual Basic 6 or VB6. In this course, Visual Basic, VB, Visual Basic 2010, Visual Basic.NET, and VB.NET are all synonymous. The immediately preceding version is Visual Basic Rev. 4.0 Copyright 2010 Object Innovations Enterprises, LLC 23

38 IntroVb Chapter 2 Hello, World Whenever learning a new programming language, a good first step is to write and run a simple program that will display a single line of text. Such a program demonstrates the basic structure of the language, including output. You must learn the pragmatics of compiling and running the program. Here is Hello, World in Visual Basic: See Hello\Hello.vb. ' Hello.vb Module Hello Sub Main() System.Console.WriteLine( _ "Hello, world") End Sub End Module Rev. 4.0 Copyright 2010 Object Innovations Enterprises, LLC 24

39 IntroVb Chapter 2 Compiling, Running (Command Line) The Visual Studio 2010 IDE (integrated development environment) was introduced in Chapter 1, and we will use it throughout the course. See Appendix A for more details. If you are using the.net SDK, you may do the following: Compile the program via the command line: vbc Hello.vb An executable file Hello.exe will be generated. To execute your program, type at the command line: Hello The program will now execute, and you should see the greeting displayed. That s all there is to it! Hello, World Rev. 4.0 Copyright 2010 Object Innovations Enterprises, LLC 25

40 IntroVb Chapter 2 Program Structure ' Hello.vb Module Hello Sub Main() System.Console.WriteLine( _ "Hello, world") End Sub End Module The program begins with a comment. A single quote mark is used to indicate the beginning of a comment; the remainder of the line is ignored by the compiler. Console applications contain a module that has a Sub Main. Sub Main is the Startup object and is called when the program begins. In Visual Basic such a unit of code is called a procedure or a method. Program units such as Module and Sub have matching End. End Module and End Sub. Visual Basic files have the extension.vb. Rev. 4.0 Copyright 2010 Object Innovations Enterprises, LLC 26

41 IntroVb Chapter 2 Statements ' Hello.vb Module Hello Sub Main() System.Console.WriteLine( _ "Hello, world") End Sub End Module Every method in Visual Basic has zero or more statements. A statement is terminated by a new line A statement may be continued onto the following line by using one or more spaces followed by the underscore character. In Visual Basic 2010 a new feature of implicit line continuation (discussed later) allows you to continue a statement on the next line without the underscore character. The Console class provides support for standard output and standard input. The method WriteLine() displays a string, followed by a new line. Rev. 4.0 Copyright 2010 Object Innovations Enterprises, LLC 27

42 IntroVb Chapter 2 Namespaces Much standard functionality in Visual Basic is provided through many classes in the.net Framework. Related classes are grouped into namespaces. The fully qualified name of a class is specified by the namespace, followed by a dot, followed by class name. System.Console An Imports statement allows a class to be referred to by its class name alone. See Hello2\Hello2.vb. ' Hello2.vb Imports System Module Hello Sub Main() Console.WriteLine("Hello, world") End Sub End Module Rev. 4.0 Copyright 2010 Object Innovations Enterprises, LLC 28

43 IntroVb Chapter 2 Project Imports Namespaces can be imported implicitly for all files in the project by listing them in the Project Imports. Right-click on the project and choose Properties. Select References from the list on the left, and scroll down until you find Imported namespaces. See Hello3, where we omit explicitly importing the System namespace, but it is still found. ' Hello3.vb Module Hello Sub Main() Console.WriteLine("Hello, world") End Sub End Module Rev. 4.0 Copyright 2010 Object Innovations Enterprises, LLC 29

44 IntroVb Chapter 2 Startup Object Another important project setting is the Startup object. To see the importance of it, open up the Hello project in the Demos folder. This is a copy of the original Hello program. Build and run it. Now, change the name of the module from Hello to Greeting. Build it. You ll get an error! 'Sub Main' was not found in 'Hello.Hello'. To fix this problem, right-click on Hello in Solution Explorer and select Properties from the context menu. Using the dropdown list, make Sub Main the startup object. Build and run. Now it should work! This alternate version of our program is saved in the Greeting directory of this chapter. Rev. 4.0 Copyright 2010 Object Innovations Enterprises, LLC 30

45 IntroVb Chapter 2 Naming Standards Visual Basic programmers must name many elements in their programs, including: variables procedures modules classes The rules govern the naming of these elements are: You may use only letters, digits, and the underscore. You must begin with either a letter or an underscore. You must have at least one letter in the name. Visual Basic names are not case sensitive. The source code editor will convert all instances of the name to the case that was used when the identifier was defined. However, the.net CLR uses case-sensitive binding. This means other.net languages that interact with your assembly must use the same case that you used when you defined the element. Examples: grosspay Sum X1 _dateofcompletion CalculateArea Find_Last_Known_Address Rev. 4.0 Copyright 2010 Object Innovations Enterprises, LLC 31

46 IntroVb Chapter 2 Keywords Visual Basic uses keywords to identify certain structural elements of a program. Keywords include: And ByRef ByVal Case Catch Class Dim Else Error For If Inherits Me Module New Optional Step Unicode Throw To Try WithEvents While Xor There are over 150 keywords in Visual Basic.NET, and the complete list can be found in the Visual Basic Language Reference in the MSDN documentation. Visual Basic allows you to use keywords as identifiers if you surround every reference to them with square brackets: Dim [Single] As Boolean Dim [Date] As String However, with a little work, you can probably think of other identifiers which convey the same meaning without using keywords: Dim Unmarried As Boolean Dim DateName As String Rev. 4.0 Copyright 2010 Object Innovations Enterprises, LLC 32

47 IntroVb Chapter 2 Multiple-File Program Structure Visual Basic programs consist of a collection of modules. The functionality in each module should be related in some way. Each module in the application is named and resides in a file with a.vb extension. Console applications must have a subroutine called Main. This defines the entry point of the program, or the point at which execution begins. See the example program UsingModules. ' DisplayModule.vb ' Collection of related procedures Module DisplayModule Public Sub SayHello() Console.WriteLine("Hello!") End Sub Public Sub RambleOn() Console.WriteLine("How now brown cow...") End Sub Public Sub SayGoodbye() Console.WriteLine("Goodbye!") End Sub End Module Rev. 4.0 Copyright 2010 Object Innovations Enterprises, LLC 33

48 IntroVb Chapter 2 Using Procedures Any code in the application can call the Public procedures defined in DisplayModule. ' UsingModules.vb ' Example of using procedures in another module Module UsingModules Sub Main() SayHello() RambleOn() SayGoodbye() End Sub End Module Rev. 4.0 Copyright 2010 Object Innovations Enterprises, LLC 34

49 IntroVb Chapter 2 Data Types The simple data types include: Visual Basic TYPE.NET FRAMEWORK TYPE MEMORY REQUIREMENTS RANGE Object System.Object 4 bytes Any type can be stored in a variable of type Object Byte System.Byte 1 byte 0 to 255 (unsigned) Char System.Char 2 bytes 0 to (unsigned) Short System.Int16 2 bytes -32,768 to 32,767 Integer System.Int32 4 bytes -2,147,483,648 to 2,147,483,647 Long System.Int64 8 bytes -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 Single System.Single 4 bytes single-precision floating point corresponding to the IEEE 754 standard Double System.Double 8 bytes double-precision floating point corresponding to the IEEE 754 standard Boolean System.Boolean 4 bytes True or False String System.String 10 bytes + (2 * string length) 0 to almost 2.1 billion Unicode characters Decimal System.Decimal 12 bytes 96-bit signed integers scaled by a variable power of 10; from 0 to 28 digits to the right of the decimal point Date System.DateTime 8 bytes January 1, 1 CE (year 1) to December 31, 9999 and times from 00:00:00 to 23:59:59 Rev. 4.0 Copyright 2010 Object Innovations Enterprises, LLC 35

50 IntroVb Chapter 2 IEEE 754 Floating Point Standard Microsoft has adopted the IEEE 754 floating-point standard for all.net languages. The standard specifies that certain operations, which previously might have produced errors, now create special values. Not-a-Number (also known as NaN) values result from dividing 0.0 by 0.0. Positive infinity values result from dividing a non-zero positive value by 0.0. Negative infinity values result from dividing a non-zero negative value by 0.0. See the example program IEEE754. Rev. 4.0 Copyright 2010 Object Innovations Enterprises, LLC 36

51 IntroVb Chapter 2 IEEE 754 (Cont'd) ' IEEE754.vb ' Example of IEEE 754 special values Module IEEE754 Sub Main() Dim top As Single Dim bottom As Single top = 0 bottom = 0 Console.WriteLine(top / bottom) top = 18 bottom = 0 Console.WriteLine(top / bottom) top = -18 bottom = 0 Console.WriteLine(top / bottom) End Sub End Module The output of the program looks like this: NaN Infinity -Infinity Rev. 4.0 Copyright 2010 Object Innovations Enterprises, LLC 37

52 IntroVb Chapter 2 Data Type Ranges Most of the numeric classes (Byte, Integer, Single, etc.) have a collection of methods and properties that can be very useful in daily programming: Properties MinValue and MaxValue can be used to determine the minimum or maximum value of a specific data type. See the example program DataRanges. Console.WriteLine("Integer Range:") Console.WriteLine(Integer.MinValue & " to " & _ Integer.MaxValue) Console.WriteLine("Single Range:") Console.WriteLine(Single.MinValue & " to " & _ Single.MaxValue) Console.WriteLine("Date Range:") Console.WriteLine(Date.MinValue & " to " & _ Date.MaxValue) output Integer Range: to Single Range: E+38 to E+38 Date Range: 1/1/ :00:00 AM to 12/31/ :59:59 PM Rev. 4.0 Copyright 2010 Object Innovations Enterprises, LLC 38

53 IntroVb Chapter 2 Literals A literal is a value that is explicitly written in code. a = 13 ' 13 is a literal name = "Natalie" ' "Natalie" is a literal Visual Basic assumes that literals are typed. The type is determined based on the way the value is expressed. If a literal is expressed without any suffix, its data type is either Integer, Double, String, or Boolean. 12 ' is an Integer literal 9.2 ' is a Double literal "Hi" ' is a String literal False ' is a Boolean literal To explicitly specify the data type of a literal, you must use a suffix to indicate its type. 12S 12I 12L 12F 12R 12D "L"C ' is a Short literal ' is an Integer literal ' is a Long literal ' is a Single literal ' is a Double literal ' is a Decimal literal ' is a Char literal Rev. 4.0 Copyright 2010 Object Innovations Enterprises, LLC 39

54 IntroVb Chapter 2 Literals (Cont'd) Visual Basic assumes that integer-type literals are decimal (base 10). You can specify that literals values are octal (base 8) or hexadecimal (base 16) by prefacing the literal with an ampersand (&) and the letter O (for octal) or H (for hexadecimal). 70 ' a decimal literal &O70 ' an octal literal - which equals ' the decimal value 56 &H70 ' a hexadecimal literal - which ' equals the decimal value 112 Date literals require a special character (#) to mark both the beginning and the ending of the literal string. This string may include a date, a time, or a date and a time. If the date is omitted, 1/1/0001 is assumed. A time value may be specified using either a 24-hour or a 12- hour value. If the time omits the AM or PM, it is assumed to be a 24-hour time. If the time is omitted, 12:00:00 AM is assumed. #9/5/1958# #9/5/ :02:00 AM# #10:02:00 AM# Rev. 4.0 Copyright 2010 Object Innovations Enterprises, LLC 40

55 IntroVb Chapter 2 Variables Variables are symbolic names that are used to represent data in a program. The variable id could hold an employee ID number and the variable pay could hold an employee s pay rate. Variables are typically defined inside a procedure using the Dim statement. The variables are local to the procedure and can be referenced only inside that procedure. These variables are created when the procedure is invoked, and destroyed when it terminates. Sub ProcessEmployeePayroll() Dim id As Integer Dim name As String Dim payrate As Decimal... End Sub Several variables (of the same type) may be declared in one Dim statement. Dim grosspay, taxes, netpay As Single Dim isvalid, iswithinrange As Boolean Variables can also be defined within a module using the Public or Private statement. These variables are created when the application is begins, and destroyed when the application terminates. Rev. 4.0 Copyright 2010 Object Innovations Enterprises, LLC 41

56 IntroVb Chapter 2 Variables (Cont'd ) The variables are either local to the module (if declared as Private) or available throughout the application (if declared Public). Module IOFunctions Private filename As String... End Module Module EmployeeFunctions Public id As Integer Public name As String Public payrate As Decimal... End Module Visual Basic allows you to select whether variable declarations are required. You may set Option Explicit On (declarations required) or Off (declarations not required) by setting the project's Compile properties. We strongly urge you to keep Option Explicit set to On!!! Rev. 4.0 Copyright 2010 Object Innovations Enterprises, LLC 42

57 IntroVb Chapter 2 Initialization of Variables Visual Basic automatically initializes variables when they are declared. All numeric variables are initialized to zero. Boolean variables are initialized to False. Dates are initialized to #1/1/ :00:00 AM# Variables may be explicitly initialized when they are declared. If a variable is initialized when it is declared, one variable may be declared per statement. Dim unitprice As Decimal = Dim x, y As Integer = 100 ' generates an error Rev. 4.0 Copyright 2010 Object Innovations Enterprises, LLC 43

58 IntroVb Chapter 2 Type Checking Most compiled programming languages are typed. That is, they check the data types of variables when they are used to make sure that the operation is allowed. Visual Basic has a compiler option (Option Strict) that can indicate the level of type-checking that should be used. When Option Strict is set to Off, Visual Basic is very flexible about the operations it allows and performs implicit conversions for you. Rev. 4.0 Copyright 2010 Object Innovations Enterprises, LLC 44

59 IntroVb Chapter 2 Weak Type Checking Example See example program WeakTypeChecking. ' Example of Weak Type Checking ' (Option Strict off) Module WeakTypeChecking Sub Main() Dim somestring As String Dim somenumber As Integer somestring = "7" ' string-to-integer assignment somenumber = somestring Console.WriteLine("{0}", somestring) Console.WriteLine("{0}", somenumber) End Sub End Module When Option Strict is set to On, Visual Basic will not perform most implicit conversions for you and will generate errors instead. When you compile the previous program, you receive the error "Option Strict disallows implicit conversions from String to Integer" on the line: somenumber = somestring Rev. 4.0 Copyright 2010 Object Innovations Enterprises, LLC 45

60 IntroVb Chapter 2 Allowed Conversions If Option Strict is On, the compiler will not necessarily generate error messages on all data type mismatches. For example, on numeric assignments, Visual Basic is primarily concerned about loss of precision. Dim somefloat As Single Dim anothernumber As Integer ' if no loss of precision occurs, "obvious" ' implicit conversions are allowed and the ' following line is legal somefloat = 4 ' if loss of precision occurs, all implicit ' conversions are disallowed and the following line ' generates a syntax error anothernumber = somefloat Rev. 4.0 Copyright 2010 Object Innovations Enterprises, LLC 46

61 IntroVb Chapter 2 Constants When writing code, you are sometimes faced with a decision regarding values that don't change. For example, assume the local sales tax rate is 8.25 percent -- how do you represent it? You might choose to represent it as a literal: tax = price *.0825 You might use a variable to represent the sales tax rate: Dim salestaxrate As Single = tax = price * salestaxrate The most desirable one approach, however, is to use a constant. Const salestaxrate As Single = tax = price * salestaxrate A constant is similar to a variable; however, the compiler generates an error if an attempt is made to change its value. Const salestaxrate As Single = salestaxrate =.0850 'error Rev. 4.0 Copyright 2010 Object Innovations Enterprises, LLC 47

62 IntroVb Chapter 2 Data Conversions Often, you need to use a value of one data type when a different data type is expected. This will require that you convert the value expressed in one data type into another data type. Visual Basic supports two types of conversions: An implicit conversion is performed silently by the compiler as needed. A conversion is safe if there is no loss of precision (ex: conversions from Integer to Long). A conversion might cause problems if there is a loss of precision (ex: conversions from Single to Long). Dim n1 As Single n1 = 46 ' implicitly convert from Integer ' to Single An explicit conversion is performed by the programmer using a conversion function. Dim s As String = "43.99" Dim n2 As Single = Convert.ToSingle(s) ' explicitly ' convert from String to Single Rev. 4.0 Copyright 2010 Object Innovations Enterprises, LLC 48

63 IntroVb Chapter 2 Data Conversions (Cont'd) There are two sets of functions that explicitly convert the data: Conversion to Visual Basic Conversion Function.NET System.Convert Method Byte CByte ToByte Short CShort ToInt16 Integer CInt ToInt32 Long CLng ToInt64 Single CSng ToSingle Double CDbl ToDouble Decimal CDec ToDecimal Char CChar ToChar String CStr ToString Date CDate ToDateTime Boolean CBool ToBoolean With Option Explicit turned On, you will need to explicitly convert many values in your application. Dim pi As Single = 3.14 ' generates a compiler ' error because 3.14 is ' a double Dim pi As Single = CSng(3.14) Dim pi As Single = Convert.ToSingle(3.14) Rev. 4.0 Copyright 2010 Object Innovations Enterprises, LLC 49

64 IntroVb Chapter 2 Operators and Expressions Now that we can declare variables, we need to be able to build complex expressions Visual Basic has a set of operators that have been enhanced since VB6. Unary operators take a single operand. A simple example is unary minus, which changes the sign of a number. Binary operators are the most common and take two operands. Examples include simple arithmetic operators such as addition and subtraction. For illustrations of the use of a number of operators, see the example program OperatorSummary. Rev. 4.0 Copyright 2010 Object Innovations Enterprises, LLC 50

65 IntroVb Chapter 2 Arithmetic Operators The arithmetic operators may be applied to any of the numerical data types of integer, floating-point, and decimal. The evaluation of any expression will always result in a value that represents the most precise operand. For example, if both operands of a multiply are Integer, the result will be Integer. However, if one operand is an Integer and the other operand is a Double, the result will be a Double because Double is a higher level of precision. Unary operators are: negate a value + indicate a positive value Dim a, b As Integer a = +b a = -b Binary operators are: + addition subtraction * multiplication / floating-point division \ integer division Mod remainder from integer division ** exponentiation Rev. 4.0 Copyright 2010 Object Innovations Enterprises, LLC 51

66 IntroVb Chapter 2 Arithmetic Operators (Cont'd) ' result is ' result is * 3 ' result is / 1.3 ' result is \ 1.3 ' result (rounded) is 2 5 / 3 ' result is \ 3 ' result is 1 5 Mod 3 ' result is ^ 1.3 ' result is You must be careful with certain mathematical operations because the result might be so large that it cannot be represented. It will generate an OverflowException runtime error. This error can be trapped. Dim n1 As Integer = Integer.MaxValue Dim n2 As Integer Try n2 = n1 * 2 Console.WriteLine("Answer = " & n2) Catch e As OverflowException Console.WriteLine( _ "Operation resulted in an overflow!") End Try Exceptions are discussed in Chapter 6. Rev. 4.0 Copyright 2010 Object Innovations Enterprises, LLC 52

67 IntroVb Chapter 2 String Operators Visual Basic allows you to use both the addition operator (+) and the concatenation operator (&) to perform string concatenation. Dim s1 As String = "Hello" Dim s2 As String = "World" Dim s3 As String s3 = s1 & " " & s2 ' result is Hello World But it is a good idea to form the habit of using the concatenation operator. In some circumstances errors can arise from the use of the addition operator, in situations where there could be confusion with numerical addition. Rev. 4.0 Copyright 2010 Object Innovations Enterprises, LLC 53

68 IntroVb Chapter 2 Relational Operators Visual Basic has six operators for making comparisons between expressions. = equality <> inequality < less than <= less than or equal to > greater than >= greater than or equal to These operators are most often used when comparing two values to decide what course of action should be taken. If a < b Then... End If If name = "Brenda" Then... End If Rev. 4.0 Copyright 2010 Object Innovations Enterprises, LLC 54

69 IntroVb Chapter 2 Logical Operators You can build complex logical expressions using the logical operators: And Or Xor Not If num < minvalue Or num > maxvalue Then Console.WriteLine("Error: number out of range") End If Dim isdone As Boolean = False Do While (Not isdone)... End While Visual Basic provides two logical operators to help evaluate expressions as efficiently as possible. These operators short circuit the evaluation process That is, they cause the evaluation process to stop examining the expression when the result of evaluation is known AndAlso OrElse Rev. 4.0 Copyright 2010 Object Innovations Enterprises, LLC 55

70 IntroVb Chapter 2 Logical Operators (Cont d) In the following If, the AndAlso operator is used to prohibit the evaluation of the second part of the expression when the value of age is NOT greater than 18. If age > 18 AndAlso state = "TX" Then... End If In the following If, the OrElse operator is used to prohibit the evaluation of the second part of the expression when the value of inputval is less than 0. If inputval < 0 OrElse inputval > 100 Then... End If Rev. 4.0 Copyright 2010 Object Innovations Enterprises, LLC 56

71 IntroVb Chapter 2 Bitwise Operators Visual Basic supports the following operators that manipulate operands at a bit level And Or Xor Not performs bitwise and performs bitwise or performs bitwise exclusive or performs one compliment operation Dim b1, b2, b3 As Byte b1 = 19 ' Bit pattern of b1 is b2 = 7 ' Bit pattern of b2 is b3 = b1 And b2 ' Bit pattern is (or 3) b3 = b1 Or b2 ' Bit pattern is (or 23) b3 = b1 Xor b2 ' Bit pattern is (or 20) b3 = Not b1 ' Bit pattern is (or 236) Rev. 4.0 Copyright 2010 Object Innovations Enterprises, LLC 57

72 IntroVb Chapter 2 Assignment Operators The assignment operator (=) is used to assign a value to a variable. x = Visual Basic also has compound assignment operators that perform operations as part of the assignment. x += 2 ' equivalent to x = x + 2 x += 2 * b ' equivalent to x = x + (2 * b) The compound assignment operators are: *= ' multiply and assign /= ' divide and assign += ' add and assign -= ' subtract and assign \= ' divide and assign &= ' concatenate and assign Rev. 4.0 Copyright 2010 Object Innovations Enterprises, LLC 58

73 IntroVb Chapter 2 Operator Precedence The precedence table for operators is shown below. It includes a few operators we have not discussed yet. Exponentiation Category Negation - Multiplication and division * / Integer division \ Modulo (remainder) arithmetic Addition, subtraction, string concatenation String concatenation Comparison Negation Logical/Bitwise conjunction Logical/Bitwise disjunction ^ Mod (string) & Operators = <> < <= > >= Like Is TypeOf..Is Not And AndAlso Or OrElse Xor A simple example of precedence is addition and multiplication. x = 5 * ' multiply first so result is 53 x = 5 * (8 + 13) ' add first so result is 105 Rev. 4.0 Copyright 2010 Object Innovations Enterprises, LLC 59

74 IntroVb Chapter 2 Console I/O Console IO is provided in the Console class in the System namespace. Although most of your professional applications will be built using Windows Forms or ASP.NET, there is value in studying console IO. It provides an easy way to learn the language without complicating the application with GUI issues. The output formatting techniques can be applied to string output in both Windows Forms and ASP.NET. Console I/O is illustrated in the example program ConsoleIO. Rev. 4.0 Copyright 2010 Object Innovations Enterprises, LLC 60

75 IntroVb Chapter 2 Console Input The Console class provides a ReadLine method to read a line of data from the standard input device. The user must press the Enter key before the input is sent to your program. ReadLine returns the string that the user typed, up to but not including the carriage return / line feed. Because ReadLine always returns a string, you must use the conversion functions discussed earlier to convert the data that is entered to the proper data type. Dim inputbuffer As String Dim payrate As Decimal Dim hrsworked As Single Console.WriteLine("Enter Pay Rate: ") inputbuffer = Console.ReadLine() payrate = Convert.ToDecimal(inputBuffer) Console.WriteLine("Enter Hours Worked: ") inputbuffer = Console.ReadLine() hrsworked = Convert.ToSingle(inputBuffer) Rev. 4.0 Copyright 2010 Object Innovations Enterprises, LLC 61

76 IntroVb Chapter 2 Console Output The Console class supports two simple methods for performing output: WriteLine writes a string followed by a new line character. Write writes just the string without the new line character. Dim x As Integer = 24 Dim y As Integer = 5 Dim z As Integer = x * y Console.Write(Convert.ToString(x) & " times " _ & Convert.ToString(y)) Console.WriteLine(" is " + Convert.ToString(z)) The output of this example is as follows: 24 times 5 is 120 Rev. 4.0 Copyright 2010 Object Innovations Enterprises, LLC 62

77 IntroVb Chapter 2 Placeholders A more convenient way to build an output string is to use placeholders, {0}, {1}, and so on are placed in an output string to indicate where actual data should appear. Console.WriteLine("{0} times {1} is {2}", x, y, z) Placeholders may contain three types of formatting information: Width specification {n,w}, where n is the placeholder number and w is the width (positive for right justification and negative for left justification). If the width specified is not large enough for the value, it will be ignored. Format specification {n:s}, where n is the placeholder number and S is a format string. Width and format specification {n,w:s}, where n is the placeholder number, w is the width, and S is a format string. Rev. 4.0 Copyright 2010 Object Innovations Enterprises, LLC 63

78 IntroVb Chapter 2 Placeholders (Cont'd) The format characters include: Character Meaning Notes D Decimal integer Can only be used with integer values E Exponential notation F Fixed-point G General (E or F) N X C Number with embedded commas Hexadecimal Currency (locale specific) Can only be used with integer values The width-only specification can be used to build tabular output. Console.WriteLine("{0,-10} {1,3}", name, age) If the above line were placed in a loop, the output might resemble this: Mary 103 Ralph 32 Jo 24 Jessie 1 The format specification is used to make numeric output more readable. It is very useful to ensure that values are displayed with the desired number of digits after the decimal place. Rev. 4.0 Copyright 2010 Object Innovations Enterprises, LLC 64

79 IntroVb Chapter 2 Placeholders (Cont'd) Dim productname As String = "BBQ Ribs (1 lb)" Dim price As Single = 8.5 Console.WriteLine("{0} is priced at $" _ & "{1,-8:F2}", productname, price) Console.WriteLine("{0} is priced at $" _ & "{1,8:F2}", productname, price) Console.WriteLine("{0} is priced at " _ & "{1,8:C}", productname, _ Convert.ToDecimal(price)) The output of the program above would look like this: BBQ Ribs (1 lb) is priced at $8.50 BBQ Ribs (1 lb) is priced at $ 8.50 BBQ Ribs (1 lb) is priced at $8.50 Rev. 4.0 Copyright 2010 Object Innovations Enterprises, LLC 65

80 IntroVb Chapter 2 A Practical Example To demonstrate the Visual Basic skills we have acquired, we will examine the SavingsCalculator program. It computes accumulations in an Individual Retirement Account with annual deposits and compound interest. The program will accept the following inputs: Annual Deposit = A Interest Rate = R Number of Years = N The following formula assumes that a deposit is made at the end of each year and that interest is compounded annually: Total Accumulation = A * ((1 + R) N - 1) / R ' Computes the total accumulated in a savings ' account when a deposit is made at the end of ' each year to the account and the interest is ' compounded annually Imports System Module SavingsCalculator Sub Main() Dim depositamount As Decimal Dim interestrate As Single Dim numyears As Integer Console.Write("Enter amount of deposit: ") depositamount = _ Convert.ToDecimal(Console.ReadLine()) Rev. 4.0 Copyright 2010 Object Innovations Enterprises, LLC 66

81 IntroVb Chapter 2 A Practical Example (Cont'd) Console.Write("Enter interest rate: ") interestrate = _ Convert.ToSingle(Console.ReadLine()) Console.Write("Enter number of years: ") numyears = _ Convert.ToInt32(Console.ReadLine()) Dim endingvalue As Decimal endingvalue = depositamount * _ (((1 + interestrate) ^ numyears) - 1) _ / interestrate Console.WriteLine("Ending Value = {0:C}", _ endingvalue) End Sub End Module The following shows the output of one run: Enter amount of deposit: 1000 Enter interest rate:.07 Enter number of years: 20 Ending Value = $ Rev. 4.0 Copyright 2010 Object Innovations Enterprises, LLC 67

82 IntroVb Chapter 2 Implicit Line Continuation Visual Basic 2010 introduced the new feature of implicit line continuation. In many cases you may continue a statement on the next line without using an underscore: After a comma After an open parentheses or before a closing parentheses After an open curly brace { or before a closing curly brace } After the concatenation operator & After assignment operators =, &=, += and so on After binary operators +, -, *, /, Mod, <, >, And, Or and so on After the Is and IsNot operators After a member qualifier operator. and before the member name After the In keyword in a For Each statement For complete rules consult the MSDN documentation. Rev. 4.0 Copyright 2010 Object Innovations Enterprises, LLC 68

83 IntroVb Chapter 2 Lab 2 New Car Loan Calculator In this lab, you will build a program that calculates the monthly payment of a car loan. Detailed instructions are contained in the Lab 2 write-up at the end of the chapter. Suggested time: 45 minutes Rev. 4.0 Copyright 2010 Object Innovations Enterprises, LLC 69

84 IntroVb Chapter 2 Summary Visual Basic is a high-level, object-oriented programming language with a variety of data types and control structures. Visual Basic supports a rich collection of data types that include Integer, Long, Single, Double, Date, and String. As with other programming languages, you can build variables and constants in Visual Basic. Visual Basic has a rich collection of operators that can be used to build complex expressions. The System.Console class includes methods console I/O, such as ReadLine and WriteLine. The System.Console class has extensive formatting capabilities controlled through placeholders. Rev. 4.0 Copyright 2010 Object Innovations Enterprises, LLC 70

85 IntroVb Chapter 2 Introduction Lab 2 New Car Loan Calculator In this lab, you will build a program that calculates the monthly payment of a new car loan. The user will be prompted for the car's purchase price, the down payment, the interest rate, and length (in months) of the loan. The program will calculate the sales tax, title fee, total purchase price of the purchase as well as the monthly payment of the new car loan. (We will return to this car loan example in Chapters 6 and 10.) Suggested Time: Root Directory: Work Directory: Solutions Directory: 45 minutes OIC\IntroVb Labs\Lab2 Chap02\CarLoan\Version1 Instructions 1. Create a new Visual Basic Console Application and name it CarLoan. Change the Module1.vb file name to CarLoan.vb and notice that the module name is automatically changed to CarLoan, and the project will start there. 2. Declare Visual Basic variables for the variables shown in the formula in Step 4 below. 3. Prompt the user for the car's purchase price, the down payment, the interest rate, and length (in months) of the loan. 4. Use the following formulas to calculate the monthly payment. where: P is the purchase price T is the sales tax TL is the title fee D is the down payment FA is the finance amount R is the interest rate (ex: 6.75) N is the number of months of the loan (ex: 24 or 60) Payment is monthly payment T = P.0625 TL = 25 Rev. 4.0 Copyright 2010 Object Innovations Enterprises, LLC 71

86 IntroVb Chapter 2 FA = P+ T + TL D Payment FA ( R /1200) = 1 (1 + R /1200) Y 5. Display the payment. 6. Build and test your application. Rev. 4.0 Copyright 2010 Object Innovations Enterprises, LLC 72

87 IntroVb Chapter 7 Chapter 7 Object-Oriented Programming Rev. 4.0 Copyright 2010 Object Innovations Enterprises, LLC 205

88 IntroVb Chapter 7 Object-Oriented Programming Objectives After completing this unit you will be able to: Describe the object-oriented features of Visual Basic. Build a class containing both methods and properties. Define and use constructors. Use shared data and shared methods. Implement a class that triggers events and handles those events in client code. Describe the operator overloading feature of Visual Basic. Rev. 4.0 Copyright 2010 Object Innovations Enterprises, LLC 206

89 IntroVb Chapter 7 Object-Oriented Programming Visual Basic.NET was designed to be a truly objectoriented language. It has capabilities that rival those of languages like Java, C++ and C#. The term object has an intuitive real-world meaning. There are concrete, tangible objects, such as a ball, an automobile, and an airplane. There are also more abstract objects that have a definite intellectual meaning, such as a committee, a patent, or an insurance contract. Objects have both attributes (or characteristics) and operations that can be performed upon them. A ball has a size, a weight, a color, and so on. Operations may be performed on the ball, such as throw, catch, and drop. There can be relationships among classes of objects. A specialization relationship exists when an object is a specialization of another type (ex: an automobile is a special kind of vehicle). A whole/part relationship exists when an object is part of another type (ex: such as an automobile consists of an engine, a chassis, wheels, and other parts). Rev. 4.0 Copyright 2010 Object Innovations Enterprises, LLC 207

90 IntroVb Chapter 7 Objects in Software Software objects correspond to objects in the real world. By explicitly describing the real-world system in terms of objects, you can understand the system more explicitly and precisely. A software system implemented in this way tends to be more faithful to the real system, and it can be changed more readily when the real system is changed. An object is a software entity containing data and related functions as a self-contained module. Objects hold state and specify behavior. The state of the object consists of the owner of the account, an ID for the account, and the account balance. The behavior of the account consists of functions to deposit or withdraw an amount from the account and to obtain an account statement. Rev. 4.0 Copyright 2010 Object Innovations Enterprises, LLC 208

91 IntroVb Chapter 7 Abstraction and Encapsulation Objects provide the means for abstraction and encapsulation. An abstraction captures the essential features of an entity, suppressing unnecessary details. All instances of an abstraction share these common features. Abstraction helps us deal with complexity. The implementation of an abstraction should be hidden from the rest of the system, or encapsulated. The public side is what the rest of the system knows, while the private side implements the public side. Data itself is private, walled off from the rest of the program and can be accessed only through functions (or methods) in the public interface. Encapsulated provides us two kinds of protection: Internal data is protected from corruption. Users of the object are protected from changes in the representation. Rev. 4.0 Copyright 2010 Object Innovations Enterprises, LLC 209

92 IntroVb Chapter 7 Classes A class groups all objects with common behavior and common structure. A class allows production of new objects of the same type. An object is an instance of some class. We refer to the process of creating an individual object as instantiation. Rev. 4.0 Copyright 2010 Object Innovations Enterprises, LLC 210

93 IntroVb Chapter 7 Creating a Class To create a class in Visual Basic, choose the Project Add Class menu. Or you may right-click over the project and choose Add Class from the context menu. Leave Class as the selected template and name the file. If you name the class BankAccount, the IDE generates a new file named BankAccount.vb. Class BankAccount End Class Rev. 4.0 Copyright 2010 Object Innovations Enterprises, LLC 211

94 IntroVb Chapter 7 Defining Data Members To define data members of a class, you typically add them as private data members. A common naming convention is to prefix the variable names with m_ to indicate that they are members of the class. Public Class BankAccount Private m_acctno As Integer Private m_name As String Private m_balance As Decimal... End Class By defining the class itself as a Public class, you are indicating that the class can be used throughout this application. The code that we discuss is in the BankAccount example, which has several versions. Rev. 4.0 Copyright 2010 Object Innovations Enterprises, LLC 212

95 IntroVb Chapter 7 Defining Methods To define the behavioral aspects of the class, you must add methods or procedures. Each method that is accessible by anyone who creates a BankAccount object is defined as a public procedure. Public Class BankAccount Private m_acctno As Integer Private m_name As String Private m_balance As Decimal Public Sub Open(ByVal acctno As Integer, _ ByVal name As String, _ Optional ByVal initialbalance As Decimal = 0) m_acctno = acctno m_name = name m_balance = initialbalance End Sub Public Function Deposit(ByVal amount As _ Decimal) As Boolean ' Check for a negative deposit If amount < 0 Then Return False ' Process deposit m_balance += amount Return True End Function Rev. 4.0 Copyright 2010 Object Innovations Enterprises, LLC 213

96 IntroVb Chapter 7 Defining Methods (Cont'd) Public Function Withdraw(ByVal amount As _ Decimal) As Boolean ' Check for a negative withdrawal If amount < 0 Then Return False ' Check for overdraft condition If amount > m_balance Then Return False ' Process withdrawal m_balance -= amount Return True End Function Public Function GetAcctNo() As Integer Return m_acctno End Function Public Function GetOwner() As String Return m_owner End Function Public Function GetBalance() As Decimal Return m_balance End Function End Class This is Version 1 of BankAccount. Rev. 4.0 Copyright 2010 Object Innovations Enterprises, LLC 214

97 IntroVb Chapter 7 Creating Objects Classes, in Visual Basic, are reference types. When you declare a variable of a class type, you are only obtaining memory for a reference to an object of the class type. No memory is allocated for the object itself. Dim myacct as BankAccount ' myacct is a reference to a BankAccount object; ' no object exists yet To create, or instantiate, an object in Visual Basic, you must use the New keyword. myacct = New BankAccount() ' a BankAccount object now exists and myacct is ' a reference to it Once an object exists, you may interact with it using any public member of the class. myacct.open (101, "Dana") myacct.deposit(1200) Console.WriteLine( _ "Account {0} has balance of {1:C}", _ myacct.getacctno(), myacct.getbalance()) The New keyword can be used when you declare the variable. Dim myacct as New BankAccount ' myacct is a reference to a BankAccount object ' was created in this declaration Rev. 4.0 Copyright 2010 Object Innovations Enterprises, LLC 215

98 IntroVb Chapter 7 Using Objects To invoke methods for a particular object, you use dot (.) notation. Dim dlwacct, mwwacct as New BankAccount dlwacct.open(158, "Dana") mwwacct.open(263, "Mark") dlwacct.deposit(150) mwwacct.deposit(150) If you attempt to reference the private members of an object from outside the implementation of a method, you will get a syntax error. mwwacct.m_balance = Error Message: BankAccount.m_balance is Private, and is not accessible in this context. Rev. 4.0 Copyright 2010 Object Innovations Enterprises, LLC 216

99 IntroVb Chapter 7 Assigning Object References It is important to have a firm understanding of the way that object references work in order to effectively write object-oriented programs in Visual Basic. Dim myacct as New BankAccount Dim youracct as New BankAccount myacct.open(1551, "Brenda", 2250) youracct.open(1552, "Glenda", 2000) Rev. 4.0 Copyright 2010 Object Innovations Enterprises, LLC 217

100 IntroVb Chapter 7 Assigning Object References (Cont'd) Because these variables are reference types, when you make an assignment to an object variable, you are only assigning the reference. There is no copying of data. youracct = myacct ' youracct now refers to same object that ' myacct does Rev. 4.0 Copyright 2010 Object Innovations Enterprises, LLC 218

101 IntroVb Chapter 7 Garbage Collection Assignment of object references in Visual Basic can lead to orphaned objects. For example, when the variable myacct in the previous example was assigned to youracct, youracct became orphaned. Such an object (or garbage ) takes up memory in the computer, which can now never be referenced. The common language runtime automatically reclaims the memory of unreferenced objects. This process is known as garbage collection. Garbage collection takes up some execution time, but it is a great convenience for programmers, helping to avoid a common program error known as a memory leak. Rev. 4.0 Copyright 2010 Object Innovations Enterprises, LLC 219

102 IntroVb Chapter 7 Me Sometimes, it is convenient to be able to access the current object reference from within a method. Visual Basic defines the keyword Me for this purpose. Me is a special variable that always refers to the current object instance. An alternative implementation of the Deposit method shown above might be as follows: Public Function Deposit(ByVal amount As Decimal) _ As Boolean ' Check for a negative deposit If amount < 0 Then Return False ' Process deposit Me.m_balance += amount Return True End Function Me refers to the object that invoked the method. myacct.deposit (100) ' in this invocation of Deposit, Me refers to ' the instance myacct youracct.deposit (100) ' in this invocation of Deposit, Me refers to ' the instance youracct Rev. 4.0 Copyright 2010 Object Innovations Enterprises, LLC 220

103 IntroVb Chapter 7 Properties Visual Basic provides a special type of procedure available to classes, modules, and structures called a property procedure. In Visual Basic, a property looks like a public data member of an object from the perspective of the user of the object. For example, if the BankAccount class has a public property called Name that accesses the account s m_name data member, you could write the following code: Dim someacct As New BankAccount someacct.open("jean C.", 850) Dim n As String n = someacct.name someacct.name = "Jean M." ' Reading the name ' Changing the name Properties allow the user of an object to interact with the object in a new way. If the property Name shown above did not exist, we would have to provide GetName and SetName methods in the BankAccount class and write the following code: Dim someacct As New BankAccount someacct.open("jean C.", 850) Dim n As String n = someacct.getname() ' Reading the name someacct.setname("jean M.") ' Changing the name Rev. 4.0 Copyright 2010 Object Innovations Enterprises, LLC 221

104 IntroVb Chapter 7 Defining Properties To define a property, its name and data type must be specified. In addition, code must be written for both the Get and Set portions of the property. Public Class BankAccount Private m_acctno As Integer Private m_name As String Private m_balance As Decimal... Public Property Name() As String Get Return m_name End Get Set(ByVal Value As String) m_name = Value End Set End Property... End Class Whenever the property Name is used on the left-hand side of an assignment statement, Visual Basic invokes the Set property. someacct.name = "Jean M." ' Changing the name If the property is used in any other context, the Get property is invoked. Dim n As String n = someacct.name ' Reading the name Rev. 4.0 Copyright 2010 Object Innovations Enterprises, LLC 222

105 IntroVb Chapter 7 Defining Properties (Cont'd) Property procedures may also have parameters passed to them. For example, this can happen when a property represents an underlying array. If a Student object maintained an array of test scores, a property called Score could be defined that allowed the following type of access: Dim zack As New Student zack.score(0) = For i = 0 to 3 Console.WriteLine("Test Score #{0} = {1}", _ i, zack.score(i)) Next The Student class, as described above, would minimally contain the following code: Public Class Student... Private m_scores(9) As Integer Public Property Score(ByVal index As Byte) _ As Integer Get Return m_scores(index) End Get Set(ByVal Value As Integer) m_scores(index) = Value End Set End Property End Class Rev. 4.0 Copyright 2010 Object Innovations Enterprises, LLC 223

106 IntroVb Chapter 7 ReadOnly Properties Sometimes, a property must be read-only. That is, it should never be used on the left-hand side of an assignment statement. In these cases, the property is designated read-only using the ReadOnly keyword, and it does not have a Set portion. Public Class BankAccount Private m_acctno As Integer... Public ReadOnly Property AcctNo() As Integer Get Return m_acctno End Get End Property... End Class Properties are illustrated in Version 2 of BankAccount. Rev. 4.0 Copyright 2010 Object Innovations Enterprises, LLC 224

107 IntroVb Chapter 7 WriteOnly Properties There are also times when a property must be writeonly. That is, you can never use it to get the value of a property. In these cases, the property is designated write-only using the WriteOnly keyword and does not have a Get portion. In this alternate version of the BankAccount class, it would define a PIN (personal identification number) that must be passed in for any withdrawal to succeed. The PIN would be defined when the account was opened. It could not be accessed, but it could be changed. Public Class BankAccount... Private m_pin as String Public WriteOnly Property PIN() As String Set(ByVal Value As String) m_pin = Value End Set End Property... End Class Rev. 4.0 Copyright 2010 Object Innovations Enterprises, LLC 225

108 IntroVb Chapter 7 Auto-Implemented Properties In Visual Basic 2010 you can implement properties more simply without explicitly creating Get and Set accessors. Parentheses are optional. Public Property Owner As String Public Property Owner() As String The Visual Basic compiler automatically creates a hidden private field called the backing field to hold the property value. The backing field is the property name preceded by an underscore character. You may use the backing field in your code. Public Sub New(ByVal n As String) _Name = n End Sub To implement a read-only property you must still proved a Get accessor. Public ReadOnly Property Balance As Decimal Get Return _Balance End Get End Property Rev. 4.0 Copyright 2010 Object Innovations Enterprises, LLC 226

109 IntroVb Chapter 7 Auto-Implemented Property Example See AutoProperty in the chapter folder. Public Class Account Public Property Name As String Private _Balance As Decimal Public ReadOnly Property Balance As Decimal Get Return _Balance End Get End Property Public Sub New(ByVal n As String, ByVal bal As Decimal) _Name = n _Balance = bal End Sub Public Sub Deposit(ByVal amount As Decimal) _Balance += amount End Sub End Class Rev. 4.0 Copyright 2010 Object Innovations Enterprises, LLC 227

110 IntroVb Chapter 7 Shared Attributes In Visual Basic, each instance of a class has its own set of unique values for the data members of the class. This type of data is called instance data. Sometimes, however, it is useful to have a data value or procedure associated with the entire class, as opposed to individual instances. Such a member is called a shared member. To define a shared data member, add the keyword Shared to the data declaration. We can modify our BankAccount class to keep track of the next available account number by adding a shared data member to the class. See Version 3. Public Class BankAccount Private m_acctno As Integer Private m_name As String Private m_balance As Decimal Private Shared m_nextaccountnum As Integer = End Class This variable is associated with the class, not with a particular instance of the class. Therefore, all instances of a BankAccount use the same variable m_nextaccountnum. Rev. 4.0 Copyright 2010 Object Innovations Enterprises, LLC 228

111 IntroVb Chapter 7 Shared Attributes (Cont'd) The shared data member can be used in methods. Public Sub Open(ByVal name As String, _ Optional ByVal initialbalance As Decimal = 0) m_acctno = m_nextaccountnum m_name = name m_balance = initialbalance m_nextaccountnum += 1 End Sub The following code illustrates one use of the new Open method. myacct.open("dana") Like instance data members, shared data members can be either Public or Private. To access a public shared member, you must use the dot notation with the name of the class replacing the name of the object. Public Class BankAccount... Public Shared BankName As String _ = "First State Bank" Private Shared m_nextaccountnum As Integer = End Sub... Console.WriteLine(BankAccount.BankName) Rev. 4.0 Copyright 2010 Object Innovations Enterprises, LLC 229

112 IntroVb Chapter 7 Shared Methods and Properties A class may also declare methods and properties as shared. To do this, add the keyword Shared to the method or property declaration. A shared method or property can be called without instantiating the class. You use the dot notation, with the class name in front of the dot. Because you can call a shared procedure without an instance, it can only access local variables, shared variables of the class, and global variables. It cannot access instance data members. Rev. 4.0 Copyright 2010 Object Innovations Enterprises, LLC 230

113 IntroVb Chapter 7 An Arithmetic Calculator Example The following example defines a class that contains nothing but Shared methods. Rather than defining a set of global functions, we have defined a Calculator class. The example is in the Calculator folder. Public Class Calculator Public Shared Function Add(ByVal op1 As _ Double, ByVal op2 As Double) As Double Return op1 + op2 End Function Public Shared Function Subtract(ByVal op1 As _ Double, ByVal op2 As Double) As Double Return op1 - op2 End Function Public Shared Function Multiply(ByVal op1 As _ Double, ByVal op2 As Double) As Double Return op1 * op2 End Function Public Shared Function Divide(ByVal op1 As _ Double, ByVal op2 As Double) As Double Return op1 / op2 End Function End Class Rev. 4.0 Copyright 2010 Object Innovations Enterprises, LLC 231

114 IntroVb Chapter 7 Arithmetic Calculator (Cont'd) The following simple program uses methods in the Calculator class to achieve specific mathematical calculations. Module Driver Sub Main() Console.Write("Enter operand 1: ") Dim operand1 As Double = _ Convert.ToDouble(Console.ReadLine()) Console.Write("Enter operand 2: ") Dim operand2 As Double = _ Convert.ToDouble(Console.ReadLine()) Console.WriteLine("Add result: {0}", _ Calculator.Add(operand1, operand2)) Console.WriteLine("Subtract result: {0}", _ Calculator.Subtract(operand1, operand2)) Console.WriteLine("Multiply result: {0}", _ Calculator.Multiply(operand1, operand2)) Console.WriteLine("Divide result: {0}", _ Calculator.Divide(operand1, operand2)) End Sub End Module Output of this test program might be as follows: Enter operand 1: 3 Enter operand 2: 9 Add result: 12 Subtract result: -6 Multiply result: 27 Divide result: Rev. 4.0 Copyright 2010 Object Innovations Enterprises, LLC 232

115 IntroVb Chapter 7 Constructors and Initialization When an object is created, what initial values are assigned to the instance data? Visual Basic because variables are automatically initialized to a default value. However, what do you do if you want to perform your own initialization? The initialization can be performed by calling some special function such as the BankAccount s Open method. The class can initialize data members in the member declarations. Public Class BankAccount Private m_acctno As Integer Private m_name As String = "Unknown" Private m_balance As Decimal... End Class The class can provide a special function called the constructor that can be used to initialize objects on a perinstance basis. Rev. 4.0 Copyright 2010 Object Innovations Enterprises, LLC 233

116 IntroVb Chapter 7 Defining Constructors A constructor is a special method that is automatically called when an object is created using New. In Visual Basic, the constructor must be defined as a subroutine named New. It is typically defined as Public, and it may define a parameter list. Public Class BankAccount Private m_acctno As Integer Private m_name As String Private m_balance As Decimal Private Shared m_nextaccountnum As Integer = 101 Public Sub New(Optional ByVal name As String _ = "", Optional ByVal initialbalance As _ Decimal = 0) m_acctno = m_nextaccountnum m_name = name m_balance = initialbalance m_nextaccountnum += 1 End Sub... End Class The New keyword is used to instantiate object instances. It is during this New operation that you pass arguments to the constructor. Dim natacct As BankAccount natacct = New BankAccount("Natalie", 1700) Rev. 4.0 Copyright 2010 Object Innovations Enterprises, LLC 234

117 IntroVb Chapter 7 Defining Constructors (Cont'd) The New keyword can also be used in the same statement that declares the reference variable. Dim britacct As New BankAccount("Brittany", 1500) Because the BankAccount constructor defines optional parameters, it could also be invoked using the following statement: Dim zackacct As New BankAccount() In this case, the variable zackacct references a BankAccount object that had the name initialized to the empty string and the balance initialized to zero. Just like other procedures in Visual Basic, constructors can be overloaded. However, you do not use the Overloads keyword on the procedure definition. Public Class BankAccount Private m_acctno As Integer Private m_owner As String Private m_balance As Decimal Private Shared m_nextaccountnum As Integer = 101 Public Sub New() m_acctno = m_nextaccountnum m_name = "" m_balance = 0 m_nextaccountnum += 1 End Sub Rev. 4.0 Copyright 2010 Object Innovations Enterprises, LLC 235

118 IntroVb Chapter 7 Defining Constructors (Cont'd) Public Sub New(ByVal name As String) m_acctno = m_nextaccountnum m_name = name m_balance = 0 m_nextaccountnum += 1 End Sub Public Sub New(ByVal name As String, _ ByVal initialbalance As Decimal) m_acctno = m_nextaccountnum m_name = name m_balance = initialbalance m_nextaccountnum += 1 End Sub... End Class The first constructor (with no parameters) allows us to create an object without specifying any initial values: Dim firstacct As New Account() The second constructor (with one String parameter) allows us to create an object by specifying an owner's name: Dim secondacct As New Account("Jen") The third constructor (with a String parameter and a Decimal parameter) allows us to create an object by specifying an owner's name and a starting balance: Dim secondacct As New Account("Jay", 1617) Rev. 4.0 Copyright 2010 Object Innovations Enterprises, LLC 236

119 IntroVb Chapter 7 Default Constructor If you do not define a constructor in your class, Visual Basic will implicitly create one for you. This constructor is called the default constructor, and it has no parameters. The compiler-supplied default constructor will initialize member variables with the value specified on the variable declaration. The default constructor is an important constructor, because it is what allows the following declaration to occur: Dim someacct As New Account However, if you provide any form of a constructor in your class, the compiler no longer supplies a version of the default constructor for you. Public Class BankAccount... Public Sub New(ByVal name As String, _ ByVal initialbalance As Decimal)... End Sub... End Class Rev. 4.0 Copyright 2010 Object Innovations Enterprises, LLC 237

120 IntroVb Chapter 7 Default Constructor (Cont'd) The following line of code compiles successfully: Dim myacct as New BankAccount("Dana", 1200) However, this next declaration generates a compiler error that says the required arguments are not provided: Dim youracct as New BankAccount() This syntax error occurs because we have provided a constructor. If we had provided no constructors, Visual Basic would have provided a default constructor. But because we provided one constructor, we must provide all allowable versions. Rev. 4.0 Copyright 2010 Object Innovations Enterprises, LLC 238

121 IntroVb Chapter 7 Shared Constructor Standard constructors are called each time an instance of a class is created. Visual Basic also provides a shared constructor that is called only once, before any object instances are created. A shared constructor is defined by prefixing the constructor with the keyword Shared. A shared constructor can take no parameters and has no access modifier. You can use a shared constructor to initialize a shared variable. Using a shared constructor, we can initialize the variable to a starting value that is calculated at runtime, or retrieved from a database. Public Class BankAccount... Private Shared m_nextaccountnum As Integer Shared Sub New() Dim rand As New Random() m_nextaccountnum = rand.next(10000) End Sub... End Class The Next method of the.net System.Random class to returns a random number that is less than the specified maximum. Rev. 4.0 Copyright 2010 Object Innovations Enterprises, LLC 239

122 IntroVb Chapter 7 Constructor Examples Our BankAccount program provides a number of illustrations of the use of constructors. In Versions 1 through 3 there is a default constructor. Version 4A provides a single constructor with optional arguments. Version 4B provides three overloaded constructors. Version 4C provides a shared constructor. Rev. 4.0 Copyright 2010 Object Innovations Enterprises, LLC 240

123 IntroVb Chapter 7 ReadOnly Members They keyword ReadOnly can be applied to instance variables to force its value to be constant. This means that it can be initialized in the constructor, but it cannot be changed in any other procedure. Any attempt to change it results in a syntax error. Although using ReadOnly isn t ever required, using it on variables that cannot change is good design Public Class BankAccount Private ReadOnly m_acctno As Integer... Public Sub New(Optional ByVal owner As String _ = "", Optional ByVal initialbalance As _ Decimal = 0) m_acctno = m_nextaccountnum... End Sub... End Class Rev. 4.0 Copyright 2010 Object Innovations Enterprises, LLC 241

124 IntroVb Chapter 7 Constant Members Visual Basic also provides the ability to define Const member declarations of a class. When a data member is defined as Const, it is also a Shared member! If it is Public, you can access it from outside the class using dot notation and the class name instead of an object variable. Unlike a ReadOnly member, a Const member cannot be changed in a constructor. Public Class BankAccount Private ReadOnly m_acctno As Integer Private m_name As String = "Unknown" Private m_balance As Decimal Private Shared m_nextaccountnum As Integer = 101 Private Const m_bankname As String _ = "First State Bank"... End Class Rev. 4.0 Copyright 2010 Object Innovations Enterprises, LLC 242

125 IntroVb Chapter 7 Events Visual Basic provides the ability for a class to fire events that can then be caught by the user using an instance of the class. Events are essentially callbacks to the user s code that occur when certain predefined data transitions occur. For example, a Database class might define the events ConnectionCompleted and ConnectionTerminated that are fired when connections are made or broken to the underlying data source. There is an important difference between events and exceptions that must be noted. Events are callbacks to a user s code that can be trapped or ignored. Exceptions must be caught -- an uncaught exception will terminate the program. We illustrate events with two more versions of our BankAccount example program. Versions 5A illustrates static event handling using the WithEvents keyword. Version 5B illustrates dynamic event handling. Rev. 4.0 Copyright 2010 Object Innovations Enterprises, LLC 243

126 IntroVb Chapter 7 Defining Events Events are defined by adding an event declaration to the class using the Event keyword. Events must have a name and an optional list of parameters that will be sent to the event handler. We will add a TransactionOccurred event to the BankAccount class. The TransactionOccurred event passes back to the user s code the type of transaction that occurred and the amount of the transaction. To provide a robust solution, we have introduced enumeration values representing the different types of transactions. Public Class BankAccount Public Enum TransactionType Deposit Withdrawal End Enum Public Event TransactionOccurred( _ ByVal transtype As TransactionType, _ ByVal amount As Decimal) Private m_acctno As Integer... End Class Rev. 4.0 Copyright 2010 Object Innovations Enterprises, LLC 244

127 IntroVb Chapter 7 Restrictions on Event Procedures There are some restrictions on event procedures. They cannot have return values. They cannot have optional parameters. They cannot have a variable length parameter list. Rev. 4.0 Copyright 2010 Object Innovations Enterprises, LLC 245

128 IntroVb Chapter 7 Raising Events Events are raised by the class when data transitions happen within an object that indicates the event should occur. To raise a specific event, the RaiseEvent statement is used. For example, the TransactionOccurred event is raised in the Deposit and Withdraw methods when they have successfully completed their activities. Public Class BankAccount... Public Function Deposit(ByVal amount As _ Decimal) As Boolean If amount < 0 Then Return False m_balance += amount RaiseEvent TransactionOccurred( _ TransactionType.Deposit, amount) Return True End Function Public Function Withdraw(ByVal amount As _ Decimal) As Boolean If amount < 0 Then Return False If amount > m_balance Then Return False m_balance -= amount RaiseEvent TransactionOccurred( _ TransactionType.Withdrawal, amount) Return True End Function End Class Rev. 4.0 Copyright 2010 Object Innovations Enterprises, LLC 246

129 IntroVb Chapter 7 Trapping Events Using WithEvents Events are trapped by the code that creates and uses a particular instance of the class. To trap events generated for a particular object, you must declare the variable using the WithEvents keyword. To listen for events on a particular object, the variable must not be declared as a local variable in a procedure. It must be declared at the class or module level. Private WithEvents dlwacct As BankAccount After the variable declaration is complete, you will notice that the variable appears in the upper-left dropdown box on the editor window. Rev. 4.0 Copyright 2010 Object Innovations Enterprises, LLC 247

130 IntroVb Chapter 7 Using WithEvents (Cont'd) You can trap events by selecting the object from the left dropdown box on the wizard bar, and then selecting the event from the right dropdown box on the wizard bar. Code for the handler function will be generated automatically. The Handles keyword indicates that this procedure is an event handler. The objectname. eventname notation that follows the keyword Handles indicates that this function is invoked when the TransactionOccurred event is generated for the dlwacct object. Public Sub dlwacct_transactionoccurred( _ ByVal transtype As BankAccount.TransactionType, _ ByVal amount As Decimal) _ Handles dlwacct.transactionoccurred Select Case transtype Case BankAccount.TransactionType.Deposit... Case BankAccount.TransactionType.Withdrawal... End Select End Sub Rev. 4.0 Copyright 2010 Object Innovations Enterprises, LLC 248

131 IntroVb Chapter 7 Trapping Events Dynamically Although trapping events using the WithEvents keyword is easy, it is somewhat limiting. The event handler is attached to a specific reference variable via static code. Although the object that the variable references can change (by creating a new instance of the class), the variable that the event handler references cannot change. Visual Basic allows you to dynamically connect and disconnect events with event handler procedures. This is done via AddHandler and RemoveHandler. For example, assume that two variables of type BankAccount were defined as follows: Private dlwacct As New BankAccount Private mwwacct As New BankAccount And assume a handler function for any TransactionOccurred event was defined as follows: Public Sub sometransactionoccurred( _ ByVal transtype As BankAccount.TransactionType, _ ByVal amount As Decimal) Select Case transtype Case BankAccount.TransactionType.Deposit... Case BankAccount.TransactionType.Withdrawal... End Select End Sub Rev. 4.0 Copyright 2010 Object Innovations Enterprises, LLC 249

132 IntroVb Chapter 7 Trapping Events Dynamically (Cont'd) You can use the AddHandler statement to indicate that the dlwacct.transactionoccurred event should be sent to the sometransactionoccurred handler: AddHandler dlwacct.transactionoccurred, _ sometransactionoccurred You can use similar logic to send the mwwtransactionoccurred event to the same handler: AddHandler mwwacct.transactionoccurred, _ sometransactionoccurred This handler function is now called regardless of whether the dlwacct object or the mwwacct object generated the event. However, because of our event design, we are now unable to determine what object occurred inside our handler function. Rev. 4.0 Copyright 2010 Object Innovations Enterprises, LLC 250

133 IntroVb Chapter 7 A Banking Example The following class represents a slight redesign in the BankAccount class. See Version 5B. The TransactionOccurred event was redesigned to carry with it information as to which object generated the event. Public Class BankAccount Public Enum TransactionType Deposit Withdrawal End Enum Public Event TransactionOccurred( _ ByVal transtype As TransactionType, _ ByVal theaccount As BankAccount, _ ByVal amount As Decimal) Private m_acctno As Integer Private m_owner As String Private m_balance As Decimal Private Shared m_nextaccountnum As Integer = 101 Public Sub New( _ Optional ByVal owner As String = "", _ Optional ByVal initialbalance As Decimal = 0) m_acctno = m_nextaccountnum m_owner = owner m_balance = initialbalance m_nextaccountnum += 1 End Sub Public Function Deposit(ByVal amount As _ Decimal) As Boolean If amount < 0 Then Return False m_balance += amount Rev. 4.0 Copyright 2010 Object Innovations Enterprises, LLC 251

134 IntroVb Chapter 7 A Banking Example (Cont'd) RaiseEvent TransactionOccurred( _ TransactionType.Deposit, Me, amount) Return True End Function Public Function Withdraw(ByVal amount As _ Decimal) As Boolean If amount < 0 Then Return False If amount > m_balance Then Return False m_balance -= amount RaiseEvent TransactionOccurred( _ TransactionType.Withdrawal, Me, amount) Return True End Function Public ReadOnly Property AcctNo() As Integer Get Return m_acctno End Get End Property Public Property Owner() As String Get Return m_owner End Get Set(ByVal Value As String) m_owner = Value End Set End Property Public ReadOnly Property Balance() As Decimal Get Return m_balance End Get End Property End Class Rev. 4.0 Copyright 2010 Object Innovations Enterprises, LLC 252

135 IntroVb Chapter 7 A Banking Example (Cont'd) Here is the key code from the driver program. Dim dlwacct, mwwacct As BankAccount Sub Main() ' Initialize the two accounts dlwacct = New BankAccount("Dana", 1250) mwwacct = New BankAccount("Mark", 750) ' Associate the two accounts with event handler AddHandler dlwacct.transactionoccured, _ AddressOf sometransactionoccured AddHandler mwwacct.transactionoccured, - AddressOf sometransactionoccured... Public Sub sometransactionoccured( _ ByVal transtype As BankAccount.TransactionType, _ ByVal theaccount As BankAccount, _ ByVal amount As Decimal) Select Case transtype Case BankAccount.TransactionType.Deposit Console.WriteLine( _ "Deposit of {0:C} recorded for {1}", _ amount, theaccount.acctno) Case BankAccount.TransactionType.Withdrawal Console.WriteLine( _ "Withdrawl of {0:C} recorded for {1}", _ amount, theaccount.acctno) End Select End Sub Rev. 4.0 Copyright 2010 Object Innovations Enterprises, LLC 253

136 IntroVb Chapter 7 ToString() in User-Defined Classes The ToString() method that is found in all data types, such as Integer, Decimal, and Date, is also available in every class you define yourself. It is inherited from the Object class (more on this in the next chapter). Below we create two instances of a BankAccount and display them using the WriteLine() method. In the first case, we directly call ToString(). In the second case, we rely upon the implicit call to ToString() to obtain the string representation for us. Dim natacct As New BankAccount("Natalie", 1700) Dim britacct As New BankAccount("Brittany", 1500) Console.WriteLine(natAcct.ToString()) Console.WriteLine(britAcct) The program compiles and runs, but the output is a little disappointing: BankAccountExample.BankAccount BankAccountExample.BankAccount The ToString() method used in our BankAccount is the one defined in the.net class Object from which class implicitly inherits. The base class Object knows nothing about our class, so it displays the name of the class. Rev. 4.0 Copyright 2010 Object Innovations Enterprises, LLC 254

137 IntroVb Chapter 7 ToString() in User-Defined Classes The ToString() method is an overridable method, which means that we may provide a version of it in our own class to display a more meaningful representation. BankAccountToString\Version1 does not override ToString(). Version 2 does override ToString(). The String.Format function uses the same formatting techniques at Console.WriteLine, but returns the string rather than displaying it. Public Class BankAccount... Public Overrides Function ToString() As String Dim retval As String retval = String.Format( _ "Account: {0}, Owner: {1}, Balance: {2:C}", _ m_acctno, m_name, m_balance) Return retval End Function End Class The test program remains the same: Dim natacct As New BankAccount("Natalie", 1700) Dim britacct As New BankAccount("Brittany", 1500) Console.WriteLine(natAcct.ToString()) Console.WriteLine(britAcct) However, the output is what we expected: Account: 101, Owner: Natalie, Balance: $1, Account: 102, Owner: Brittany, Balance: $1, Rev. 4.0 Copyright 2010 Object Innovations Enterprises, LLC 255

138 IntroVb Chapter 7 Operator Overloading Beginning with.net 2.0, you can overload operators in Visual Basic, as has been possible in languages such as C++ and C#. You cannot create new operators, but you can overload many of the existing operators to be an alias for a shared method. The overloaded operator is used just like the built-in operator is used, except it is applied to a custom data type. As an example, consider ClockOperator. Here is the test program that uses the + operator that has been overloaded to do clock arithmetic (modulo 12). Note that the compiler then automatically also overloads += for you. Dim c1 As Clock = New Clock(17) Console.WriteLine("c1 = {0}", c1.hour) Dim c2 As Clock = New Clock(10) Console.WriteLine("c2 = {0}", c2.hour) Dim c3 As Clock = c1 + c2 Console.WriteLine("c3 = {0}", c3.hour) c3 += 1 Console.WriteLine("c3 + 1 = {0}", c3.hour) Here is the output: c1 = 5 c2 = 10 c3 = 3 c3 + 1 = 4 Rev. 4.0 Copyright 2010 Object Innovations Enterprises, LLC 256

139 IntroVb Chapter 7 Operator Overloading (Cont d) Here is the code defining the class Clock. Note use of the keyword Operator. Public Class Clock Private m_hour As Integer Public Sub New(ByVal h As Integer) m_hour = h Mod 12 If m_hour = 0 Then m_hour = 12 End If End Sub Public Property Hour() As Integer Get Return m_hour End Get Set m_hour = Value End Set End Property Public Shared Operator +(ByVal c1 As Clock, _ ByVal c2 As Clock) As Clock Dim h As Integer = c1.hour + c2.hour Dim c3 As Clock = New Clock(h) Return c3 End Operator Public Shared Operator +(ByVal c1 As Clock, _ ByVal h2 As Integer) As Clock Dim h As Integer = c1.hour + h2 Dim c3 As Clock = New Clock(h) Return c3 End Operator End Class Rev. 4.0 Copyright 2010 Object Innovations Enterprises, LLC 257

140 IntroVb Chapter 7 Lab 7 Building a Class in Visual Basic In this lab, you will build a class that represents a Student object in a university setting. The class will maintain information about the student and their GPA. Detailed instructions are contained in the Lab 7 write-up at the end of the chapter. Suggested time: 75 minutes Rev. 4.0 Copyright 2010 Object Innovations Enterprises, LLC 258

141 IntroVb Chapter 7 Summary Classes can represent user-defined data types. A class can be thought of as a template from which individual instances, or objects, can be created. Classes support encapsulation through attributes and methods. Typically, attributes are defined as Private members and methods are defined as Public members of a class. Because classes are reference types, when you declare a variable of a class type, you are obtaining memory only for a reference to an object of the class type. No memory for the object is allocated itself until New is invoked. The common language runtime automatically reclaims the memory of orphaned, or unreferenced, objects. This process is known as garbage collection. Initialization of objects is performed in special procedures called constructors. Visual Basic also provides the ability for objects to generate events to notify users of that event that some predefined action occurred. You can overload built-in operators in your custom classes. Rev. 4.0 Copyright 2010 Object Innovations Enterprises, LLC 259

142 IntroVb Chapter 7 Introduction Lab 7 Building a Class in Visual Basic In this lab, you will build a class that represents a student at a university. It will have several properties and methods that allow you to manipulate student objects. Then you will build a main procedure that declares instances of the student class and uses them. Suggested Time: Root Directory: 75 minutes OIC\IntroVb Directories: Labs\Lab7 Work area Chap07\University\Version1 Solution Chap07\University\Version2 Solution to optional Instructions 1. Create a new Visual Basic Console Application and name it University. Change the module file name to University.vb. 2. Add a class module to the project and name the class Student. Define the following members: Attribute name classification gradepoints hrsattempted hrsearned Property Name Classification HoursEarned GPA Data Type String String (will hold Freshman, Sophomore, Junior, or Senior) Short Byte Byte Notes It gets or puts the name attribute It gets the classification attribute (ReadOnly) It gets the hrsearned attribute (ReadOnly) It gets the value gradepoints / hrsattempted (ReadOnly) Method Notes New It accepts a value for the name attribute. CompleteCourse It accepts two parameters: grade (character) and hours (byte). If the grade is an A, it is worth 4 points. A B is worth 3 points, etc. An F is worth 0 points. Add the grade's point value times the Rev. 4.0 Copyright 2010 Object Innovations Enterprises, LLC 260

143 IntroVb Chapter 7 hours for the class to gradepoints (ex: a 3 hour course with an A is worth 12 points). Add the hours to hrsattempted. If the grade is passing, also add the hours to hrsearned. Finally, change the classification to one of the following: Freshman if hrsearned < 32 Sophmore if hrsearned < 64 Junior if hrsearned < 96 Senior all other cases 3. In Main, declare two instances of a Student. Have each student complete several courses. Using the properties, display the student's classification, GPA, etc. after each operation. 4. Build and test your application. [Optional] Add two events to the Student class. The first event should be called GPAWarning and should be raised whenever a student completes a course and their GPA falls below 2.0. The second event should be called TransitionToUpperclassman and occurs when the number of hours earned becomes 60 or more. In the Main subroutine, catch these events and display an informative message. Rev. 4.0 Copyright 2010 Object Innovations Enterprises, LLC 261

144 IntroVb Chapter 7 Rev. 4.0 Copyright 2010 Object Innovations Enterprises, LLC 262

145 IntroVb Chapter 13 Chapter 13 Database Programming Rev. 4.0 Copyright 2010 Object Innovations Enterprises, LLC 473

146 IntroVb Chapter 13 Database Programming Objectives After completing this unit you will be able to: Understand the key concepts in the ADO.NET data access programming model. Use the ADO.NET classes to build applications that retrieve and update data from a data source. Use Visual Studio 2010 to efficiently implement database programs. Use the data binding facilities in Windows Forms and ADO.NET. Rev. 4.0 Copyright 2010 Object Innovations Enterprises, LLC 474

147 IntroVb Chapter 13 ADO.NET The.NET Framework has introduced a new set of database classes designed for loosely coupled, distributed architectures. These classes are referred to as ADO.NET. ADO.NET uses the same access mechanisms for local, client-server, and Internet database access. It can be used to examine data as relational data or as hierarchical (XML) data. ADO.NET can pass data to any component using XML and does not require a continuous connection to the database. A more traditional connected access model is also available. Rev. 4.0 Copyright 2010 Object Innovations Enterprises, LLC 475

148 IntroVb Chapter 13 ADO.NET Architecture The DataSet class is the central component of the disconnected architecture. A dataset can be populated from either a database or from an XML stream. From the perspective of the user of the dataset, the original source of the data is immaterial. A consistent programming model is used for all application interaction with the dataset. The second key component of ADO.NET architecture is the.net Data Provider, which provides access to a database, and can be used to populate a dataset. A data provider can also be used directly by an application to support a connected mode of database access. Rev. 4.0 Copyright 2010 Object Innovations Enterprises, LLC 476

149 IntroVb Chapter 13 ADO.NET Architecture (Cont d) The figure illustrates the overall architecture of ADO.NET. Application Connected Access Disconnected Access DataSet.NET Data Provider XML Data Database Rev. 4.0 Copyright 2010 Object Innovations Enterprises, LLC 477

150 IntroVb Chapter 13.NET Data Providers A.NET data provider is used for connecting to a database. It provides classes that can be used to execute commands and to retrieve results. The results are either used directly by the application, or else they are placed in a dataset. A.NET data provider implements four key interfaces: IDbConnection is used to establish a connection to a specific data source. IDbCommand is used to execute a command at a data source. IDataReader provides an efficient way to read a stream of data from a data source. The data access provided by a data reader is forward-only and read-only. IDbDataAdapter is used to populate a dataset from a data source. The ADO.NET architecture specifies these interfaces, and different implementations can be created to facilitate working with different data sources. A.NET data provider is analogous to an OLE DB provider, but the two should not be confused. An OLE DB provider implements COM interfaces, and a.net data provider implements.net interfaces. Rev. 4.0 Copyright 2010 Object Innovations Enterprises, LLC 478

151 IntroVb Chapter 13 Programming with ADO.NET Interfaces In order to make your programs more portable, you should endeavor to program with the interfaces rather than using specific classes directly. In our example programs we will illustrate using interfaces to talk to an Access database (using the OleDb data provider) and a SQL Server database (using the SqlServer data provider). Classes of the OleDb provider have a prefix of OleDb, and classes of the SqlServer provider have a prefix of Sql. The table shows a number of parallel classes between the two data providers and the corresponding interfaces. Interface OleDb SQL Server IDbConnection OleDbConnection SqlConnection IDbCommand OleDbCommand SqlCommand IDataReader OleDbDataReader SqlDataReader IDbDataAdatpter OleDbDataAdapter SqlDataAdapter IDbTransaction OleDbTransaction SqlTransaction IDataParameter OleDbParameter SqlParameter Classes such as DataSet which are independent of any data provider do not have any prefix. Rev. 4.0 Copyright 2010 Object Innovations Enterprises, LLC 479

152 IntroVb Chapter 13.NET Namespaces ADO.NET classes are found in the following namespaces: System.Data consists of classes that constitute most of the ADO.NET architecture. System.Data.OleDb contains classes that provide database access using the OLE DB data provider. System.Data.SqlClient contains classes that provide database access using the SQL Server data provider. System.Data.OracleClient contains classes that provide database access using the Oracle data provider. Both Microsoft and Oracle supply data providers for Oracle. System.Data.SqlTypes contains classes that represent data types used by SQL Server. System.Data.Common contains classes that are shared by data providers. Rev. 4.0 Copyright 2010 Object Innovations Enterprises, LLC 480

153 IntroVb Chapter 13 Connected Data Access The connection class (OleDbConnection or SqlConnection) is used to manage the connection to the data source. It has properties ConnectionString, ConnectionTimeout, and so forth. There are methods for Open, Close, transaction management, etc. A connection string is used to identify the information the object needs to connect to the database. You can specify the connection string when you construct the connection object, or by setting its properties. A connection string contains a series of argument = value statements separated by semicolons. To program in a manner that is independent of the data source, you should obtain an interface reference of type IDbConnection after creating the connection object, and you should program against this interface reference. Rev. 4.0 Copyright 2010 Object Innovations Enterprises, LLC 481

154 IntroVb Chapter 13 Sample Database Our sample database, SimpleBank, stores account information for a small bank. Two tables: 1. Account stores information about bank accounts. Columns are AccountId, Owner, AccountType and Balance. The primary key is AccountId. 2. BankTransaction stores information about account transactions. Columns are AccountId, XactType, Amount and ToAccountId. There is a parent/child relationship between the Account and BankTransaction tables. There are SQL Server 2008 and Access versions of this database. We will be using SQL Server 2008 Express Edition, which comes automatically with Visual Studio There is also built-in support for Access as well, so no special DBMS software is required for this chapter. The database files are in the folder OIC\Data. The SQL Server database file is SimpleBank.mdf The Access database file is SimpleBank.mdb. Rev. 4.0 Copyright 2010 Object Innovations Enterprises, LLC 482

155 IntroVb Chapter 13 Example: Connecting to SQL Server See SqlConnectOnly. Imports System.Data.SqlClient Module Module1 Sub Main() Dim connstr As String = "Data Source=.\SQLEXPRESS;AttachDbFilename= c:\oic\data\simplebank.mdf; Integrated Security=True;User Instance=True" Dim conn As New SqlConnection() conn.connectionstring = connstr Console.WriteLine( "Using SQL Server to access SimpleBank") Console.WriteLine( "Database state: " & conn.state.tostring()) conn.open() Console.WriteLine( "Database state: " & conn.state.tostring()) End Sub End Class Output: Using SQL Server to access SimpleBank Database state: Closed Database state: Open Rev. 4.0 Copyright 2010 Object Innovations Enterprises, LLC 483

156 IntroVb Chapter 13 ADO.NET Class Libraries To run a program that uses the ADO.NET classes, you must be sure to set references to the appropriate class libraries. The following libraries should usually be included: System.dll System.Data.dll System.Xml.dll (needed when working with datasets) References to these libraries are set up automatically when you create a Windows Form or Console in Visual Studio The figure shows the references in a Console project, as created by Visual Studio Rev. 4.0 Copyright 2010 Object Innovations Enterprises, LLC 484

157 IntroVb Chapter 13 Connecting to an OLE DB Data Provider To connect to an OLE DB data provider instead, you need to change the namespace you are importing and instantiate an object of the OleDbConnection class. You must provide a connection string appropriate to your OLE DB provider. We are going to use the Jet OLE DB provider, which can be used for connecting to an Access database. The program JetConnectOnly illustrates connecting to the Access database SimpleBank.mdb Imports System.Data.OleDb Module Module1 Sub Main() Dim connstr As String = "Provider=Microsoft.Jet.OLEDB.4.0;" & "Data Source=C:\OIC\Data\SimpleBank.mdb" Dim conn As New OleDbConnection() conn.connectionstring = connstr Console.WriteLine( "Using Access DB SimpleBank.mdb") Console.WriteLine( "Database state: " & conn.state.tostring()) conn.open() Console.WriteLine( "Database state: " & conn.state.tostring()) End Sub End Class Rev. 4.0 Copyright 2010 Object Innovations Enterprises, LLC 485

158 IntroVb Chapter 13 Importing a Namespace Visual Studio 2010 offers a nice trick to make it easier to import a needed namespace in your program. Place the cursor over the.net Framework class that is not recognized and press Ctrl +. ( control dot ). A popup gives us an option to import the namespace. Just press Enter. The necessary namespace will be imported. Imports System.Data.OleDb Module Module1 Sub Main() Dim connstr As String =... Dim conn As New OleDbConnection() Rev. 4.0 Copyright 2010 Object Innovations Enterprises, LLC 486

159 IntroVb Chapter 13 Using Commands After we have opened a connection to a data source, we can create a command object, which will execute a query against a data source. Depending on our data source, we will create either a SqlCommand object or an OleDbCommand object. In either case, we will initialize an interface reference of type IDbCommand, which will be used in the rest of our code, again promoting relative independence from the data source. The table summarizes some of the principle properties and methods of IDbCommand. Property or Method CommandText CommandTimeout CommandType Connection Parameters Cancel ExecuteReader ExecuteNonQuery Description Text of command to run against the data source Wait time before terminating command attempt How CommandText is interpreted (e.g. Text, StoredProcedure) The IDbConnection used by the command The parameters collection Cancel the execution of an IDbCommand Obtain an IDataReader for retrieving data (SELECT) Execute a SQL command such as INSERT, DELETE, etc. Rev. 4.0 Copyright 2010 Object Innovations Enterprises, LLC 487

160 IntroVb Chapter 13 Creating a Command Object The code fragments shown below are from the ConnectedSql program, which illustrates performing various database operations on the SimpleBank database. For an Access version, see ConnectedJet. The following code illustrates creating a command object and returning an IDbCommand interface reference. Private Function CreateCommand( ByVal query As String) As IDbCommand Return New SqlCommand(query, sqlconn) End Function Note that we return an interface reference, not an object reference. Using the generic interface IDbCommand makes the rest of our program independent of a particular database. Rev. 4.0 Copyright 2010 Object Innovations Enterprises, LLC 488

161 IntroVb Chapter 13 ExecuteNonQuery The following code illustrates executing a SQL DELETE statement using a command object. We create a query string for the command, and obtain a command object for this command. The call to ExecuteNonQuery returns the number of rows that were updated. Private Sub RemoveAccount( ByVal id As Integer) Dim query As String = "delete from Account where AccountId = " & id Dim command As IDbCommand = CreateCommand(query) Dim numrow As Integer = _ command.executenonquery() Console.WriteLine("{0} rows updated", numrow) End Sub Rev. 4.0 Copyright 2010 Object Innovations Enterprises, LLC 489

162 IntroVb Chapter 13 Using a Data Reader After we have created a command object, we can call the ExecuteReader method to return an IDataReader. With the data reader we can obtain a read-only, forward-only stream of data. This method is suitable for reading large amounts of data, because only one row at a time is stored in memory. When you are done with the data reader, you should explicitly close it. Any output parameters or return values of the command object will not be available until after the data reader has been closed. Data readers have an Item property that can be used for accessing the current record. The Item property accepts either an integer (representing a column number) or a string (representing a column name). The Item property is the default property and can be omitted if desired. The Read method is used to advance the data reader to the next row. When it is created, a data reader is positioned before the first row. You must call Read before accessing any data. Read returns true if there are more rows, and otherwise false. Rev. 4.0 Copyright 2010 Object Innovations Enterprises, LLC 490

163 IntroVb Chapter 13 Data Reader: Code Example The code illustrates using a data reader to display results of a SELECT query. Sample program is still in ConnectedSql. Private Sub ShowList() Dim query As String = "select * from Account" Dim command As IDbCommand = CreateCommand(query) Dim reader As IDataReader = command.executereader() Do While reader.read() Console.WriteLine( "{0,3} {1,-10} {2:C} {3}", reader("accountid"), reader("owner") _ reader("balance"), reader("accounttype")) Loop reader.close() End Sub Rev. 4.0 Copyright 2010 Object Innovations Enterprises, LLC 491

164 IntroVb Chapter 13 Lab 13A Bank Database Program In this lab, you will build a Windows Forms application that provides a graphical user interface to the Simple Bank database. Detailed instructions are contained in the Lab 13A write-up at the end of the chapter. Suggested time: 30 minutes Rev. 4.0 Copyright 2010 Object Innovations Enterprises, LLC 492

165 IntroVb Chapter 13 Disconnected Datasets A DataSet stores data in memory and provides a consistent relational programming model that is the same whatever the original source of the data. Thus, a DataSet contains a collection of tables and relationships between tables. Each table contains a primary key and collections of columns and constraints, which define the schema of the table, and a collection of rows, which make up the data stored in the table. DataSet Relationships Tables Relation Table Constraints Primary Key Columns Rows Constraint Data Column Data Row Rev. 4.0 Copyright 2010 Object Innovations Enterprises, LLC 493

166 IntroVb Chapter 13 Data Adapters A data adapter provides a bridge between a disconnected dataset and its data source. Each.NET data provider provides its own implementation of the interface IDbDataAdapter. The OLE DB data provider has the class OleDbDataAdapter, and the SQL data provider has the class SqlDataAdapter. A data adapter has properties for SelectCommand, InsertCommand, UpdateCommand, and DeleteCommand. These properties identify the SQL needed to retrieve data, add data, change data, or remove data from the data source. A data adapter has the Fill method to place data into a dataset. It has the Update command to update the data source using data from the dataset. Rev. 4.0 Copyright 2010 Object Innovations Enterprises, LLC 494

167 IntroVb Chapter 13 Data Bound Controls All of our demonstration programs so far have been console applications. We have done this in order to focus on the coding of database functionality, without being distracted by issues concerning user interface. Also, by catching exceptions in our command loop, we are able to conveniently display exception information, making it easy for you to experiment and observe the results, even for exceptional situations. Naturally, in practice you will want to create an attractive user interface, either as a Windows application or a Web application. In this section we will give a brief introduction to providing a graphical user interface to a database application using Windows Forms. There are two approaches that can be followed. The first is to write specific code to populate controls with data that has been retrieved from a database. You did that in Lab 13A. The second is to use data bound controls. We will illustrate this second approach by showing how to bind a dataset to a DataGridView control. Rev. 4.0 Copyright 2010 Object Innovations Enterprises, LLC 495

168 IntroVb Chapter 13 DataGridView Control The DataGridView control is new with.net 2.0 and is the preferred control for interacting with tabular data. Binding data to a DataGridView control is simple, and is often simply a matter of setting the DataSource property. It will bind to any class that implements one of the following interfaces: IList, including one-dimensional arrays and array lists IListSource, including DataSet and DataTable IBindingList, such as GenericBindingList IBindingListView, such as BindingSource Most frequently, you will bind to a BindingSource component, which is in turn bound to a data source. Visual Studio 2010 provides a wizard interface to facilitate establishing bindings. Rev. 4.0 Copyright 2010 Object Innovations Enterprises, LLC 496

169 IntroVb Chapter 13 DataGridView Sample Program We ll demonstrate using a DataGridView control in an application that accesses the SmallPub database. You should have SQL Server 2008 Express edition installed. The database file SmallPub.mdf is located in the directory c:\oic\data. This database is for use by a small publisher of technical books. There are two tables: Category maintains a list of categories for books. Book is a list of the books published. The sample program shows a list of all books in a category that is selected from a dropdown list. See ShowBooks\Step2. Rev. 4.0 Copyright 2010 Object Innovations Enterprises, LLC 497

170 IntroVb Chapter 13 DataGridView Demo We ll create this application from scratch, using Visual Studio. 1. Create a new Windows Forms Application ShowBooks. Save the solution of the new project in the Demos directory. 2. Increase the width of the main form somewhat, comparable to what is shown in the screen capture in the preceding page. 3. Drag a DataGridView control from the Data group in the ToolBox onto your form. Note that the smart tag for this control is expanded, allowing you to set up a binding. 4. Drop down Choose Data Source and click on Add Project Data Source. Rev. 4.0 Copyright 2010 Object Innovations Enterprises, LLC 498

171 IntroVb Chapter 13 DataGridView Demo (Cont d) 5. Make sure that Database is specified for the source of the data. Click Next. 6. A screen comes up letting you choose the kind of database model to use. 7. Choose Dataset. Rev. 4.0 Copyright 2010 Object Innovations Enterprises, LLC 499

172 IntroVb Chapter 13 DataGridView Demo (Cont d) 8. In the next screen, to choose the connection, click the New Connection button. 9. In the Add Connection dialog, make sure that SQL Server Database File is selected as the data source, and browse to the SmallPub.mdf file. You may test the connection if you wish. 10. Click OK. Back in the wizard, click Next. 11. You will be asked if you want to copy the database file to your project. Say No. Rev. 4.0 Copyright 2010 Object Innovations Enterprises, LLC 500

173 IntroVb Chapter 13 DataGridView Demo (Cont d) 12. You will be asked if you want to save the connection string to the application configuration file. Leave the checkbox at Yes, and click Next. 13. In Choose your database objects expand Tables and check both the Book and Category tables. 14. Click Finish. 15. You will now have an opportunity to select which table in the DataSet you want to bind to the DataGridView control. (If the smart tag has closed, open it up again to finish binding the control to the project data source that you have just created.) Rev. 4.0 Copyright 2010 Object Innovations Enterprises, LLC 501

174 IntroVb Chapter 13 DataGridView Demo (Cont d) 16. If necessary, open up the Project Data Sources to show the SmallPubDataSet and its tables. 17. Click on the link to the Book table. 18. Visual Studio will now create several components for you: a DataSet, a BindingSource, and a TableAdapter. See the screen capture on the following page. (At some point you will also want to resize the DataGridView control to provide adequate width for displaying all the columns.) Rev. 4.0 Copyright 2010 Object Innovations Enterprises, LLC 502

175 IntroVb Chapter 13 DataGridView Demo (Cont d) 19. You will now see column headings displayed in the grid. Build and run. You will see all the books displayed. Rev. 4.0 Copyright 2010 Object Innovations Enterprises, LLC 503

176 IntroVb Chapter 13 Performing a Query We would now like to provide a facility for the user to show only the books in a particular category. 20. Open up the smart tag again, and click on the Add Query link Name the query BooksByCat and specify a WHERE clause, making the entire query: SELECT BookId, Title, CategoryId, Price FROM dbo.book WHERE CategoryId 1 I encountered an apparent bug in Visual Studio, not seeing the bottom two links at first. They appeared after I tried some of the other links. Rev. 4.0 Copyright 2010 Object Innovations Enterprises, LLC 504

177 IntroVb Chapter 13 Performing a Query (Cont d) 22. When you are satisfied with your query, click OK. Rev. 4.0 Copyright 2010 Object Innovations Enterprises, LLC 505

178 IntroVb Chapter 13 Performing a Query (Cont d) 23. A ToolStrip is added to your form to run the query. Build and run your application. Try entering a particular CategoryId, and then click the BooksByCat button. 24. You have a simple database query application, and you have not written a line of code! 25. Make any desired tweaks to the UI, such as making the DataGridView control larger. Change the title of your form to Show Books By Category. You are now at Step Examine Step 2, which replaces the automatically generated ToolStrip interface with your own combobox for displaying the available categories. Rev. 4.0 Copyright 2010 Object Innovations Enterprises, LLC 506

179 IntroVb Chapter 13 Lab 13B Data Binding In this lab, you will enhance the data binding demo program to specify the CategoryId by means of a dropdown combobox, which is bound to the Category table of the DataSet. You can use the code generated by Visual Studio for the ToolStrip as a guide for your own code. When done, you can delete the ToolStrip. Detailed instructions are contained in the Lab 13B write-up at the end of the chapter. Suggested time: 30 minutes Rev. 4.0 Copyright 2010 Object Innovations Enterprises, LLC 507

180 IntroVb Chapter 13 Summary ADO.NET provides a set of classes that can be used to interact with data providers. You can access data sources in either a connected or disconnected mode. The DataReader can be used to build interact with a data source in a connected mode. The DataSet can be used to interact with data from a data source without maintaining a constant connection to the data source. The DataSet can be populated from a database using a DataAdapter. You can use Visual Studio 2010 to efficiently implement database programs. You can easily display data from a dataset on a form by binding the dataset to a DataGridView control. Rev. 4.0 Copyright 2010 Object Innovations Enterprises, LLC 508

181 IntroVb Chapter 13 Introduction Lab 13A Bank Database Program In this lab, you will build a Windows Forms application that provides a graphical user interface to the Simple Bank database. Suggested Time: 45 minutes Root Directory: OIC\IntroVb Directories: Labs\Lab13A\BankGui (do your work here) Chap13\BankGui\Step1 (backup of starter code) Chap13\BankGui\Step2 (answer) Database: OIC\Data\SimpleBank.mdf Instructions 1. Build and run the starter program. Examine the code, and observe the following features. a. The class DB encapsulates all the ADO.NET code. In general, this is a good design, as opposed to having database code directly in the GUI. All the methods are shared, so it will not be necessary to instantiate a DB object. Rev. 4.0 Copyright 2010 Object Innovations Enterprises, LLC 509

182 IntroVb Chapter 13 b. The class Account encapsulates an account. c. The file Form1.vb provides the user interface, with handlers for the Read, Previous and Next buttons. The Read button will read the database into a List(Of Account), which can be traversed by the Previous and Next buttons. The number of accounts in the list will be shown in a status bar at the bottom of the form. 2. Provide a method AddAccount() in the DB class. It will be similar to the corresponding method in the ConnectedSql() program, but it will not do any output. Instead, it will return the number of rows updated to the calling program. Public Shared Function AddAccount(ByVal owner As String, _ ByVal bal As Decimal, ByVal atype As String) As Integer Dim query As String = "insert into Account " & _ "(Owner, Balance, AccountType) values('" & owner & "', " & _ bal & ", '" & atype & "')" Dim command As IDbCommand = CreateCommand(query) conn.open() Dim numrow As Integer = command.executenonquery() conn.close() Return numrow End Function 3. Provide a handler for the Add button in which you will call the AddAccount() method. Private Sub btnadd_click(byval sender As System.Object, _ ByVal e As System.EventArgs) Handles btnadd.click Dim owner As String = txtowner.text Dim balance As Decimal = Convert.ToDecimal(txtBalance.Text) Dim acctype As String = "" If radchecking.checked Then acctype = "C" ElseIf radsavings.checked Then acctype = "S" End If Dim numrow As Integer = DB.AddAccount(owner, balance, acctype) Dim msg As String = String.Format("{0} rows updated", numrow) MessageBox.Show(msg, "Simple Bank") End Sub 4. You may build and test at this point. Note that you do not have to specify an ID for a new account, as the database will generate an ID automatically for you. After you have added an account, you may click Read. You should see in the status bar that there is now one more account, and by clicking Next repeatedly, you will come to the new account. 5. In a similar manner add a method RemoveAccount() and use it to implement a handler for the Delete button. Finally, add a method UpdateAccount() and use it to implement a handler for the Update button. Build and test. Rev. 4.0 Copyright 2010 Object Innovations Enterprises, LLC 510

183 IntroVb Chapter 13 Introduction Lab 13B Data Binding In this lab, you will enhance the data binding demo program to specify the CategoryId by means of a dropdown combobox, which is bound to the Category table of the DataSet. You can use the code generated by Visual Studio for the ToolStrip as a guide for your own code. When done, you can delete the ToolStrip. Suggested Time: 30 minutes Root Directory: OIC\IntroVb Directories: Labs\Lab13B\ShowBooks Demos\ShowBooks Chap13\ShowBooks\Step1 Chap13\ShowBooks\Step2 (do your work here starter code) (continue in-class demo) (backup of starter code) (answer) Instructions 1. If you completed the in-class demo, you may continue working in the Demos\ShowBooks directory. Otherwise, you can use the starter code provided in the lab directory. Build and run your program to make sure it is working. 2. Drag a ComboBox onto the form. Change the name to cmbcat. Make sure that DropDownStyle is DropDown. 3. Open the smart tag. Check Use Data Bound Items. Several fields for Data Binding Mode open up. Rev. 4.0 Copyright 2010 Object Innovations Enterprises, LLC 511

184 IntroVb Chapter For the Data Source, select the Category table in SmallPubDataSet, which you can find by opening up Other Data Sources and then Project Data Sources. 5. This will set up a binding through a new BindingSource, CategoryBindingSource. Display Member should be Description and Value Member should be CategoryId. 6. Build and run the program. You should see that the combobox is displaying the categories, but at this point it is not linked to populating the DataGridView control. Rev. 4.0 Copyright 2010 Object Innovations Enterprises, LLC 512

Evaluation Copy. Visual Basic Essentials. Student Guide Revision 4.5. Object Innovations Course 4202

Evaluation Copy. Visual Basic Essentials. Student Guide Revision 4.5. Object Innovations Course 4202 Visual Basic Essentials Student Guide Revision 4.5 Object Innovations Course 4202 Visual Basic Essentials Rev. 4.5 Student Guide Information in this document is subject to change without notice. Companies,

More information

Object-Oriented Programming in C# (VS 2012)

Object-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 information

Object-Oriented Programming in C# (VS 2015)

Object-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 information

C++/CLI Essentials. Student Guide Revision 1.0. Object Innovations Course 431

C++/CLI Essentials. Student Guide Revision 1.0. Object Innovations Course 431 C++/CLI Essentials Student Guide Revision 1.0 Object Innovations Course 431 C++/CLI Essentials Rev. 1.0 Student Guide Information in this document is subject to change without notice. Companies, names

More information

Evaluation Copy. C# Essentials. Student Guide Revision 4.5. Object Innovations Course 4102

Evaluation Copy. C# Essentials. Student Guide Revision 4.5. Object Innovations Course 4102 C# Essentials Student Guide Revision 4.5 Object Innovations Course 4102 C# Essentials Rev. 4.5 Student Guide Information in this document is subject to change without notice. Companies, names and data

More information

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

Unit 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 information

Object-Oriented Programming in Visual Basic

Object-Oriented Programming in Visual Basic Object-Oriented Programming in Visual Basic Dana L. Wyatt Robert J. Oberg Student Guide Revision 2.1 Object Innovations Course 420 Object-Oriented Programming in Visual Basic Rev. 2.1 Student Guide Information

More information

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

IT 374 C# and Applications/ IT695 C# Data Structures IT 374 C# and Applications/ IT695 C# Data Structures Module 2.1: Introduction to C# App Programming Xianrong (Shawn) Zheng Spring 2017 1 Outline Introduction Creating a Simple App String Interpolation

More information

Chapter 1 Getting Started

Chapter 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 information

Darshan Institute of Engineering & Technology for Diploma Studies

Darshan 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 information

C# Programming: From Problem Analysis to Program Design. Fourth Edition

C# Programming: From Problem Analysis to Program Design. Fourth Edition C# Programming: From Problem Analysis to Program Design Fourth Edition Preface xxi INTRODUCTION TO COMPUTING AND PROGRAMMING 1 History of Computers 2 System and Application Software 4 System Software 4

More information

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

Microsoft. 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 information

EEE-425 Programming Languages (2013) 1

EEE-425 Programming Languages (2013) 1 2 Computer programming: creating a sequence of instructions to enable the computer to do something Programmers do not use machine language when creating computer programs. Instead, programmers tend to

More information

EVALUATION COPY. Unauthorized reproduction or distribution is prohibitied C# ESSENTIALS

EVALUATION COPY. Unauthorized reproduction or distribution is prohibitied C# ESSENTIALS C# ESSENTIALS C# Essentials Rev. 4.8 Student Guide Information in this document is subject to change without notice. Companies, names and data used in examples herein are fictitious unless otherwise noted.

More information

Chapters and Appendix F are PDF documents posted online at the book s Companion Website (located at

Chapters and Appendix F are PDF documents posted online at the book s Companion Website (located at Contents Chapters 16 27 and Appendix F are PDF documents posted online at the book s Companion Website (located at www.pearsonhighered.com/deitel/). Preface Before You Begin xix xxix 1 Introduction to

More information

Chapters are PDF documents posted online at the book s Companion Website (located at

Chapters are PDF documents posted online at the book s Companion Website (located at vbhtp6printonlytoc.fm Page ix Wednesday, February 27, 2013 11:59 AM Chapters 16 31 are PDF documents posted online at the book s Companion Website (located at www.pearsonhighered.com/deitel/). Preface

More information

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

Introduce 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 information

Prerequisites: The student should have programming experience in a high-level language. ITCourseware, LLC Page 1. Object-Oriented Programming in C#

Prerequisites: The student should have programming experience in a high-level language. ITCourseware, LLC Page 1. Object-Oriented Programming in C# Microsoft s.net is a revolutionary advance in programming technology that greatly simplifies application development and is a good match for the emerging paradigm of Web-based services, as opposed to proprietary

More information

EVALUATION COPY. Object-Oriented Programming in C# Student Guide Revision 4.6. Unauthorized reproduction or distribution is prohibited.

EVALUATION COPY. Object-Oriented Programming in C# Student Guide Revision 4.6. Unauthorized reproduction or distribution is prohibited. Object-Oriented Programming in C# Student Guide Revision 4.6 Object Innovations Course 4101 Object-Oriented Programming in C# Rev. 4.6 Student Guide Information in this document is subject to change without

More information

C# Programming in the.net Framework

C# 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 information

Client-Side Web Technologies. JavaScript Part I

Client-Side Web Technologies. JavaScript Part I Client-Side Web Technologies JavaScript Part I JavaScript First appeared in 1996 in Netscape Navigator Main purpose was to handle input validation that was currently being done server-side Now a powerful

More information

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

Contents. 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 information

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

UNIT 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 information

Learning C# 3.0. Jesse Liberty and Brian MacDonald O'REILLY. Beijing Cambridge Farnham Köln Sebastopol Taipei Tokyo

Learning C# 3.0. Jesse Liberty and Brian MacDonald O'REILLY. Beijing Cambridge Farnham Köln Sebastopol Taipei Tokyo Learning C# 3.0 Jesse Liberty and Brian MacDonald O'REILLY Beijing Cambridge Farnham Köln Sebastopol Taipei Tokyo Table of Contents Preface xv 1. C# and.net Programming 1 Installing C# Express 2 C# 3.0

More information

.Net Technologies. Components of.net Framework

.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 information

Fundamental C# Programming

Fundamental C# Programming Part 1 Fundamental C# Programming In this section you will find: Chapter 1: Introduction to C# Chapter 2: Basic C# Programming Chapter 3: Expressions and Operators Chapter 4: Decisions, Loops, and Preprocessor

More information

Programming in Visual Basic with Microsoft Visual Studio 2010

Programming in Visual Basic with Microsoft Visual Studio 2010 Programming in Visual Basic with Microsoft Visual Studio 2010 Course 10550; 5 Days, Instructor-led Course Description This course teaches you Visual Basic language syntax, program structure, and implementation

More information

Introduction to Visual Basic and Visual C++ Arithmetic Expression. Arithmetic Expression. Using Arithmetic Expression. Lesson 4.

Introduction to Visual Basic and Visual C++ Arithmetic Expression. Arithmetic Expression. Using Arithmetic Expression. Lesson 4. Introduction to Visual Basic and Visual C++ Arithmetic Expression Lesson 4 Calculation I154-1-A A @ Peter Lo 2010 1 I154-1-A A @ Peter Lo 2010 2 Arithmetic Expression Using Arithmetic Expression Calculations

More information

Fig 1.1.NET Framework Architecture Block Diagram

Fig 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 information

Visual C# Instructor s Manual Table of Contents

Visual 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 information

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

PROGRAMMING 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 information

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

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 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 information

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

COPYRIGHTED 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 information

Object Oriented Programming with Visual Basic.Net

Object Oriented Programming with Visual Basic.Net Object Oriented Programming with Visual Basic.Net By: Dr. Hossein Hakimzadeh Computer Science and Informatics IU South Bend (c) Copyright 2007 to 2015 H. Hakimzadeh 1 What do we need to learn in order

More information

DOT NET Syllabus (6 Months)

DOT NET Syllabus (6 Months) DOT NET Syllabus (6 Months) THE COMMON LANGUAGE RUNTIME (C.L.R.) CLR Architecture and Services The.Net Intermediate Language (IL) Just- In- Time Compilation and CLS Disassembling.Net Application to IL

More information

Introduction to Programming Using Java (98-388)

Introduction 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 information

Weiss Chapter 1 terminology (parenthesized numbers are page numbers)

Weiss Chapter 1 terminology (parenthesized numbers are page numbers) Weiss Chapter 1 terminology (parenthesized numbers are page numbers) assignment operators In Java, used to alter the value of a variable. These operators include =, +=, -=, *=, and /=. (9) autoincrement

More information

Microsoft Visual C# Step by Step. John Sharp

Microsoft Visual C# Step by Step. John Sharp Microsoft Visual C# 2013 Step by Step John Sharp Introduction xix PART I INTRODUCING MICROSOFT VISUAL C# AND MICROSOFT VISUAL STUDIO 2013 Chapter 1 Welcome to C# 3 Beginning programming with the Visual

More information

CHAPTER 1: INTRODUCING C# 3

CHAPTER 1: INTRODUCING C# 3 INTRODUCTION xix PART I: THE OOP LANGUAGE CHAPTER 1: INTRODUCING C# 3 What Is the.net Framework? 4 What s in the.net Framework? 4 Writing Applications Using the.net Framework 5 What Is C#? 8 Applications

More information

"Charting the Course... MOC Programming in C# with Microsoft Visual Studio Course Summary

Charting the Course... MOC Programming in C# with Microsoft Visual Studio Course Summary Course Summary NOTE - The course delivery has been updated to Visual Studio 2013 and.net Framework 4.5! Description The course focuses on C# program structure, language syntax, and implementation details

More information

Course Syllabus C # Course Title. Who should attend? Course Description

Course Syllabus C # Course Title. Who should attend? Course Description Course Title C # Course Description C # is an elegant and type-safe object-oriented language that enables developers to build a variety of secure and robust applications that run on the.net Framework.

More information

A Fast Review of C Essentials Part I

A Fast Review of C Essentials Part I A Fast Review of C Essentials Part I Structural Programming by Z. Cihan TAYSI Outline Program development C Essentials Functions Variables & constants Names Formatting Comments Preprocessor Data types

More information

UNIT- 3 Introduction to C++

UNIT- 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 information

DOT NET SYLLABUS FOR 6 MONTHS

DOT NET SYLLABUS FOR 6 MONTHS DOT NET SYLLABUS FOR 6 MONTHS INTRODUCTION TO.NET Domain of.net D.N.A. Architecture One Tier Two Tier Three Tier N-Tier THE COMMON LANGUAGE RUNTIME (C.L.R.) CLR Architecture and Services The.Net Intermediate

More information

Data Types. Strings Variables Declaration Statements Named Constant Assignment Statements Intrinsic (Built-in) Functions

Data Types. Strings Variables Declaration Statements Named Constant Assignment Statements Intrinsic (Built-in) Functions Data and Operations Outline Data Types Arithmetic Operations Strings Variables Declaration Statements Named Constant Assignment Statements Intrinsic (Built-in) Functions Data and Operations 1 Data and

More information

The C++ Language. Arizona State University 1

The C++ Language. Arizona State University 1 The C++ Language CSE100 Principles of Programming with C++ (based off Chapter 2 slides by Pearson) Ryan Dougherty Arizona State University http://www.public.asu.edu/~redoughe/ Arizona State University

More information

Visual Basic 2008 How to Program, 4/E Outline

Visual Basic 2008 How to Program, 4/E Outline vbhtp4_outline.fm Page ix Monday, December 17, 2007 4:40 PM Visual Basic 2008 How to Program, 4/E Outline ( subject to change) current as of 12/17/07. As the contents change, we ll post updates at www.deitel.com/books/vbhtp4/.

More information

Outline. Data and Operations. Data Types. Integral Types

Outline. Data and Operations. Data Types. Integral Types Outline Data and Operations Data Types Arithmetic Operations Strings Variables Declaration Statements Named Constant Assignment Statements Intrinsic (Built-in) Functions Data and Operations Data and Operations

More information

Creating and Running Your First C# Program

Creating and Running Your First C# Program Creating and Running Your First C# Program : http://eembdersler.wordpress.com Choose the EEE-425Programming Languages (Fall) Textbook reading schedule Pdf lecture notes Updated class syllabus Midterm and

More information

Programming Language 2 (PL2)

Programming 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 information

EEE-425 Programming Languages (2013) 1

EEE-425 Programming Languages (2013) 1 Creating and Running Your First C# Program : http://eembdersler.wordpress.com Choose the EEE-425Programming Languages (Fall) Textbook reading schedule Pdf lecture notes Updated class syllabus Midterm and

More information

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

Agenda & 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 information

BASIC ELEMENTS OF A COMPUTER PROGRAM

BASIC 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 information

Data and Operations. Outline

Data and Operations. Outline Data and Operations Data and Operations 1 Outline Data Types Arithmetic Operations Strings Variables Declaration Statements Named Constant Assignment Statements Intrinsic (Built-in) Functions Data and

More information

CS2900 Introductory Programming with Python and C++ Kevin Squire LtCol Joel Young Fall 2007

CS2900 Introductory Programming with Python and C++ Kevin Squire LtCol Joel Young Fall 2007 CS2900 Introductory Programming with Python and C++ Kevin Squire LtCol Joel Young Fall 2007 Course Web Site http://www.nps.navy.mil/cs/facultypages/squire/cs2900 All course related materials will be posted

More information

Student Guide Revision 1.0

Student Guide Revision 1.0 Robert J. Oberg Student Guide Revision 1.0 Object Innovations Course 411 C# Essentials Rev. 1.0 Student Guide Information in this document is subject to change without notice. Companies, names and data

More information

Programming in C# with Microsoft Visual Studio 2010

Programming in C# with Microsoft Visual Studio 2010 Programming in C# with Microsoft Visual Studio 2010 Course 10266; 5 Days, Instructor-led Course Description: The course focuses on C# program structure, language syntax, and implementation details with.net

More information

Advanced Object-Oriented Programming. 11 Features. C# Programming: From Problem Analysis to Program Design. 4th Edition

Advanced Object-Oriented Programming. 11 Features. C# Programming: From Problem Analysis to Program Design. 4th Edition 11 Features Advanced Object-Oriented Programming C# Programming: From Problem Analysis to Program Design C# Programming: From Problem Analysis to Program Design 1 4th Edition Chapter Objectives Learn the

More information

CHAPTER 1: INTRODUCTION TO THE IDE 3

CHAPTER 1: INTRODUCTION TO THE IDE 3 INTRODUCTION xxvii PART I: IDE CHAPTER 1: INTRODUCTION TO THE IDE 3 Introducing the IDE 3 Different IDE Appearances 4 IDE Configurations 5 Projects and Solutions 6 Starting the IDE 6 Creating a Project

More information

C# Syllabus. MS.NET Framework Introduction

C# Syllabus. MS.NET Framework Introduction C# Syllabus MS.NET Framework Introduction The.NET Framework - an Overview Framework Components Framework Versions Types of Applications which can be developed using MS.NET MS.NET Base Class Library MS.NET

More information

Introduction to C# Applications

Introduction to C# Applications 1 2 3 Introduction to C# Applications OBJECTIVES To write simple C# applications To write statements that input and output data to the screen. To declare and use data of various types. To write decision-making

More information

Index COPYRIGHTED MATERIAL

Index COPYRIGHTED MATERIAL Index COPYRIGHTED MATERIAL Note to the Reader: Throughout this index boldfaced page numbers indicate primary discussions of a topic. Italicized page numbers indicate illustrations. A abstract classes

More information

10/9/2012. Sample C# program:

10/9/2012. Sample C# program: Creating and Running Your First C# Program Text Book : C# Programming From Problem Analysis to Program design, Barbara Doyle Grading : Homeworks 20% Lecture Presentation 20% Final : % 20 Project : 40%

More information

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

Uka 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 information

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

Getting 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 information

Object-Oriented Programming in C# Evaluation Copy. Student Guide Revision 4.5. Object Innovations Course 4101

Object-Oriented Programming in C# Evaluation Copy. Student Guide Revision 4.5. Object Innovations Course 4101 Object-Oriented Programming in C# Student Guide Revision 4.5 Object Innovations Course 4101 Object-Oriented Programming in C# Rev. 4.5 Student Guide Information in this document is subject to change without

More information

INTRODUCTION TO.NET. Domain of.net D.N.A. Architecture One Tier Two Tier Three Tier N-Tier THE COMMON LANGUAGE RUNTIME (C.L.R.)

INTRODUCTION TO.NET. Domain of.net D.N.A. Architecture One Tier Two Tier Three Tier N-Tier THE COMMON LANGUAGE RUNTIME (C.L.R.) INTRODUCTION TO.NET Domain of.net D.N.A. Architecture One Tier Two Tier Three Tier N-Tier THE COMMON LANGUAGE RUNTIME (C.L.R.) CLR Architecture and Services The.Net Intermediate Language (IL) Just- In-

More information

[CHAPTER] 1 INTRODUCTION 1

[CHAPTER] 1 INTRODUCTION 1 FM_TOC C7817 47493 1/28/11 9:29 AM Page iii Table of Contents [CHAPTER] 1 INTRODUCTION 1 1.1 Two Fundamental Ideas of Computer Science: Algorithms and Information Processing...2 1.1.1 Algorithms...2 1.1.2

More information

Chapter 17. Fundamental Concepts Expressed in JavaScript

Chapter 17. Fundamental Concepts Expressed in JavaScript Chapter 17 Fundamental Concepts Expressed in JavaScript Learning Objectives Tell the difference between name, value, and variable List three basic data types and the rules for specifying them in a program

More information

Visual C# 2008 How to Program, 3/E Outline

Visual C# 2008 How to Program, 3/E Outline vcsharp2008htp_outline.fm Page ix Monday, December 17, 2007 4:39 PM Visual C# 2008 How to Program, 3/E Outline ( subject to change) current as of 12/17/07. As the contents change, we ll post updates at

More information

Fundamental of Programming (C)

Fundamental of Programming (C) Borrowed from lecturer notes by Omid Jafarinezhad Fundamental of Programming (C) Lecturer: Vahid Khodabakhshi Lecture 3 Constants, Variables, Data Types, And Operations Department of Computer Engineering

More information

After completing this appendix, you will be able to:

After completing this appendix, you will be able to: 1418835463_AppendixA.qxd 5/22/06 02:31 PM Page 879 A P P E N D I X A A DEBUGGING After completing this appendix, you will be able to: Describe the types of programming errors Trace statement execution

More information

Microsoft Visual Basic 2015: Reloaded

Microsoft 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 information

Introduction 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. 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 information

The PCAT Programming Language Reference Manual

The PCAT Programming Language Reference Manual The PCAT Programming Language Reference Manual Andrew Tolmach and Jingke Li Dept. of Computer Science Portland State University September 27, 1995 (revised October 15, 2002) 1 Introduction The PCAT language

More information

Introduction to Data Entry and Data Types

Introduction 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 information

EDIABAS BEST/2 LANGUAGE DESCRIPTION. VERSION 6b. Electronic Diagnostic Basic System EDIABAS - BEST/2 LANGUAGE DESCRIPTION

EDIABAS BEST/2 LANGUAGE DESCRIPTION. VERSION 6b. Electronic Diagnostic Basic System EDIABAS - BEST/2 LANGUAGE DESCRIPTION EDIABAS Electronic Diagnostic Basic System BEST/2 LANGUAGE DESCRIPTION VERSION 6b Copyright BMW AG, created by Softing AG BEST2SPC.DOC CONTENTS CONTENTS...2 1. INTRODUCTION TO BEST/2...5 2. TEXT CONVENTIONS...6

More information

VBScript: Math Functions

VBScript: Math Functions C h a p t e r 3 VBScript: Math Functions In this chapter, you will learn how to use the following VBScript functions to World Class standards: 1. Writing Math Equations in VBScripts 2. Beginning a New

More information

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

Hierarchical 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 information

Course Hours

Course 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 information

ASP.NET Web Forms Programming Using Visual Basic.NET

ASP.NET Web Forms Programming Using Visual Basic.NET ASP.NET Web Forms Programming Using Visual Basic.NET Duration: 35 hours Price: $750 Delivery Option: Attend training via an on-demand, self-paced platform paired with personal instructor facilitation.

More information

University of Technology. Laser & Optoelectronics Engineering Department. C++ Lab.

University of Technology. Laser & Optoelectronics Engineering Department. C++ Lab. University of Technology Laser & Optoelectronics Engineering Department C++ Lab. Second week Variables Data Types. The usefulness of the "Hello World" programs shown in the previous section is quite questionable.

More information

An overview about DroidBasic For Android

An overview about DroidBasic For Android An overview about DroidBasic For Android from February 25, 2013 Contents An overview about DroidBasic For Android...1 Object-Oriented...2 Event-Driven...2 DroidBasic Framework...2 The Integrated Development

More information

Scenario Manager User Guide. Release September 2013

Scenario Manager User Guide. Release September 2013 Scenario Manager User Guide Release 6.2.1 September 2013 Scenario Manager User Guide Release 6.2.1 September 2013 Document Control Number: 9MN12-62110017 Document Number: SMUG-13-FCCM-0017-6.2.1-01 Oracle

More information

JScript Reference. Contents

JScript Reference. Contents JScript Reference Contents Exploring the JScript Language JScript Example Altium Designer and Borland Delphi Run Time Libraries Server Processes JScript Source Files PRJSCR, JS and DFM files About JScript

More information

Outsource. Laboratories. Introduction to Programming with Microsoft Visual Basic.NET. Outsource Laboratories Press

Outsource. Laboratories. Introduction to Programming with Microsoft Visual Basic.NET. Outsource Laboratories Press Outsource Laboratories Introduction to Programming with Microsoft Visual Basic.NET Outsource Laboratories Press Copyright 2004 Outsource Laboratories Press. Printed in the United States of America ISBN

More information

Dot Net Online Training

Dot Net Online Training chakraitsolutions.com http://chakraitsolutions.com/dotnet-online-training/ Dot Net Online Training DOT NET Online Training CHAKRA IT SOLUTIONS TO LEARN ABOUT OUR UNIQUE TRAINING PROCESS: Title : Dot Net

More information

2/5/2018. Expressions are Used to Perform Calculations. ECE 220: Computer Systems & Programming. Our Class Focuses on Four Types of Operator in C

2/5/2018. Expressions are Used to Perform Calculations. ECE 220: Computer Systems & Programming. Our Class Focuses on Four Types of Operator in C University of Illinois at Urbana-Champaign Dept. of Electrical and Computer Engineering ECE 220: Computer Systems & Programming Expressions and Operators in C (Partially a Review) Expressions are Used

More information

Absolute C++ Walter Savitch

Absolute 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 information

Pace University. Fundamental Concepts of CS121 1

Pace 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 information

Objectives. 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++ 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 information

Chapter 2: Basic Elements of C++

Chapter 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 information

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

Chapter 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 information

C Language Part 1 Digital Computer Concept and Practice Copyright 2012 by Jaejin Lee

C Language Part 1 Digital Computer Concept and Practice Copyright 2012 by Jaejin Lee C Language Part 1 (Minor modifications by the instructor) References C for Python Programmers, by Carl Burch, 2011. http://www.toves.org/books/cpy/ The C Programming Language. 2nd ed., Kernighan, Brian,

More information

Operators and Expressions

Operators and Expressions Operators and Expressions Conversions. Widening and Narrowing Primitive Conversions Widening and Narrowing Reference Conversions Conversions up the type hierarchy are called widening reference conversions

More information

Chapter 2 Using Data. Instructor s Manual Table of Contents. At a Glance. Overview. Objectives. Teaching Tips. Quick Quizzes. Class Discussion Topics

Chapter 2 Using Data. Instructor s Manual Table of Contents. At a Glance. Overview. Objectives. Teaching Tips. Quick Quizzes. Class Discussion Topics Java Programming, Sixth Edition 2-1 Chapter 2 Using Data At a Glance Instructor s Manual Table of Contents Overview Objectives Teaching Tips Quick Quizzes Class Discussion Topics Additional Projects Additional

More information

10266 Programming in C Sharp with Microsoft Visual Studio 2010

10266 Programming in C Sharp with Microsoft Visual Studio 2010 10266 Programming in C Sharp with Microsoft Visual Studio 2010 Course Number: 10266A Category: Visual Studio 2010 Duration: 5 days Course Description The course focuses on C# program structure, language

More information

AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS

AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS PAUL L. BAILEY Abstract. This documents amalgamates various descriptions found on the internet, mostly from Oracle or Wikipedia. Very little of this

More information

Language Reference Manual simplicity

Language Reference Manual simplicity Language Reference Manual simplicity Course: COMS S4115 Professor: Dr. Stephen Edwards TA: Graham Gobieski Date: July 20, 2016 Group members Rui Gu rg2970 Adam Hadar anh2130 Zachary Moffitt znm2104 Suzanna

More information

Variable Scope The Main() Function Struct Functions Overloading Functions Using Delegates Chapter 7: Debugging and Error Handling Debugging in Visual

Variable Scope The Main() Function Struct Functions Overloading Functions Using Delegates Chapter 7: Debugging and Error Handling Debugging in Visual Table of Contents Title Page Introduction Who This Book Is For What This Book Covers How This Book Is Structured What You Need to Use This Book Conventions Source Code Errata p2p.wrox.com Part I: The OOP

More information