You are on page 1of 229

O F F I C I A L

M I C R O S O F T

L E A R N I N G

P R O D U C T

10550A
Programming in Visual Basic with
Microsoft Visual Studio 2010
Companion Content

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

Product Number: 10550A


Part Number : X17-53002
Released: 04/2011

Programming in Visual Basic with Microsoft Visual Studio 2010

1-1

Module 1
Introducing Visual Basic and the .NET Framework
Contents:
Lesson 1: Introduction to the .NET Framework 4

Lesson 2: Creating Projects Within Visual Studio 2010

11

Lesson 3: Writing a Visual Basic Application

16

Lesson 4: Building a Graphical Application

19

Lesson 5: Documenting an Application

24

Lesson 6: Debugging Applications by Using Visual Studio 2010

27

Module Reviews and Takeaways

29

Lab Review Questions and Answers

32

1-2

Programming in Visual Basic with Microsoft Visual Studio 2010

Lesson 1

Introduction to the .NET Framework 4


Contents:
Question and Answers

Additional Reading

Programming in Visual Basic with Microsoft Visual Studio 2010

Question and Answers


What Is the .NET Framework 4?
Question: What is the purpose of the .NET Framework 4 and the three main components it
provides?
Answer: The .NET Framework 4 provides a comprehensive development platform that offers
a fast and efficient way to build applications and services. The .NET Framework 4 consists of
three components: the common language runtime, the .NET Framework class library, and
development frameworks.

What Is Visual Basic?


Question: Which programming languages have you used?
Answer: Ask students which languages they have used.

What Is an Assembly?
Question: Why would you choose to distribute an assembly rather than distribute the source
code?
Answer: An assembly is a compiled unit that can contain multiple functional components
that is ready to run. If you distributed raw source files, end users would have to compile the
code before they could run the application.

How the CLR Loads, Compiles, and Runs Assemblies


Question: What steps does the CLR perform when you run your application?
Answer: The CLR performs the following steps:
1.
2.
3.

The Class Loader locates and loads all assemblies that the application requires. The assemblies
will already be compiled into MSIL.
The MSIL-to-native compiler verifies the MSIL code and then compiles all assemblies into
machine code ready for execution.
The Code Manager loads the executable assembly and runs the Main method.

What Tools Does the .NET Framework Provide?


Question: You have created two applications that both use an assembly called
Contoso.ReportGenerator.dll. Both applications will run on the same machine. What is the
best approach to share the Contoso.ReportGenerator.dll assembly and which tool would
you use?
Answer: You would install the assembly into the Global Assembly Cache (GAC) by using the
Gacutil.exe tool.

1-3

1-4

Programming in Visual Basic with Microsoft Visual Studio 2010

Additional Reading
What Is the .NET Framework 4?
For more information about the .NET Framework, see Microsoft .NET.

What Is Visual Basic?


For more information about Visual Basic 2010, see Visual Basic.
For more information about the new features of Visual Basic2010, see What's New in Visual Basic
2010.

What Is an Assembly?
For more information about the purpose and features of assemblies, see Assemblies in the
Common Language Runtime.
For more information about assembly versioning, see Assembly Versioning.
For more information about assembly signing, see SignTool.exe (Sign Tool).

What Tools Does the .NET Framework Provide?


For more information about the tools that the .NET Framework provides, see .NET Framework
Tools.

Programming in Visual Basic with Microsoft Visual Studio 2010

1-5

Lesson 2

Creating Projects Within Visual Studio 2010


Contents:
Question and Answers

Detailed Demonstration Steps

1-6

Programming in Visual Basic with Microsoft Visual Studio 2010

Question and Answers


Key Features of Visual Studio 2010
Question: What are the main reasons for choosing Visual Studio 2010 over a text editor such
as Notepad++?
Answer: Answers should include:

The intuitive IDE in Visual Studio 2010.

Visual Studio 2010 supports rapid application development with Designer and Code Editor
windows, and wizards.

Visual Studio 2010 provides debugging features that help you fix any bugs in your code.

Visual Studio 2010 offers help and support with IntelliSense, code snippets, and the Visual Studio
community.

Templates in Visual Studio 2010


Question: What project templates would you use for each of the following:

A client application that will run on a Windows-based computer.

A library of functionality that you want to use in other applications.

A Web site that you will host on an Internet Information Services (IIS) Web server.

Answer: Possible answers include:

For a client application, you could use the WPF Application and Windows Forms Application
templates.

For a library, you could use the Class Library template.

For a Web site, you could use the ASP.NET Web Application and ASP.NET MVC 2 Application
templates.

Structure of Visual Studio Projects and Solutions


Question: What role does the .sln file play in Visual Studio solutions?
Answer: .NET solutions act as a wrapper for solution settings and your .NET projects. .NET
solutions also enable you to build multiple projects without having to open multiple
instances of Visual Studio.

Creating a .NET Framework Application


Question: What is the purpose of code snippets?
Answer: Code snippets remove the need for developers to repeatedly type common code
constructs.

Building and Running a .NET Framework Application


Question: Describe two ways to build and run a .NET Framework application.
Answer: You can build a .NET application by using Visual Studio or csc.exe on the command
line.

Programming in Visual Basic with Microsoft Visual Studio 2010

Demonstration: Disassembling a .NET Framework Assembly


Question: When developing a .NET Framework application, how would you find Ildasm
useful?
Answer: It is very useful to try to understand the inner workings of .NET, especially when you
are developing your first .NET application. You can use Ildasm to inspect assemblies that you
build and see how the compiler generates MSIL code.

1-7

1-8

Programming in Visual Basic with Microsoft Visual Studio 2010

Detailed Demonstration Steps


Demonstration: Disassembling a .NET Framework Assembly
Detailed demonstration steps
Task 1: Run an existing .NET application
1.

Right-click the Start menu, and then click Open Windows Explorer.

2.

In Windows Explorer, browse to the D:\Demofiles\Mod1\Demo1 folder, and then double-click


MyFirstApplication.exe.

3.

In the MyFirstApplication window, point out:

The title of the Command Prompt window, which is set to My First Application.

The text Hello, this is my first .NET application which is displayed in the Command
Prompt window.

That the Command Prompt window does not automatically close until you click the
Close button.

4.

Close the MyFirstApplication window.

Task 2: Open Ildasm


1.

Right-click the Start menu, and then click Open Windows Explorer.

2.

In Windows Explorer, browse to the C:\Program Files (x86)\Microsoft


SDKs\Windows\v7.0A\Bin folder, and then double-click ildasm.exe.

Task 3: Disassemble an existing .NET Framework assembly


1.

In the IL DASM window, on the File menu, click Open.

2.

In the Open dialog box, browse to the D:\Demofiles\Mod1\Demo1 folder, and then doubleclick MyFirstApplication.exe.

Task 4: Examine the disassembled .NET Framework assembly


1.

In the IL DASM window, in the output pane, point to the Manifest node and explain that this is
stored alongside the assembly.

2.

Double-click the Manifest node.

3.

In the Manifest window, show students the following, and then close the Manifest window:

.publickeytokenexplain that this is the public key for the assembly.

.verexplain that this is the version of the assembly.

4.

Expand the MyFirstApplication node, and then point to the MyFirstApplication.Module1


module. Explain that this is the only module or class in the MyFirstApplication assembly.

5.

Expand the MyFirstApplication.Module1 node.

6.

Point to the .custom instance void[...] node, and then explain that this is the default and
static/shared constructor for the MyFirstApplication.Module1 module.

7.

Point to the Main : void() node, and then explain that this is the default startup method
provided in the MyFirstApplication.Module1 module, and is the entry point into the

Programming in Visual Basic with Microsoft Visual Studio 2010

application. Inform students that the concept of the Main method will be covered in the next
lesson.
8.

Double-click the Main : void() node.

9.

In the MyFirstApplication.Module1::Main : void() window, show students the following, and


then close the MyFirstApplication.Module1::Main : void() window:

void [mscorlib]System.Console::set_Title(string)explain that this is a call to display


the text My First Application in the Command Prompt title bar.

void [mscorlib]System.Console::WriteLine(string)explain that this is a call to


display the text Hello, this is my first .NET application in the Command Prompt
window.

valuetype [mscorlib]System.ConsoleKeyInfo
[mscorlib]System.Console::ReadKey()explain that this is a call to stop the Command
Prompt window from closing until the user presses a key.

10. On the File menu, click Exit.

1-9

1-10

Programming in Visual Basic with Microsoft Visual Studio 2010

Lesson 3

Writing a Visual Basic Application


Contents:
Question and Answers

Additional Reading

Programming in Visual Basic with Microsoft Visual Studio 2010

Question and Answers


What Are Modules, Classes, and Namespaces?
Question: In your console application, you want to use the Console class, which is part of
the System namespace. How do you bring the System namespace into scope?
Answer: You could use the Imports statement to bring the System namespace into scope.

Structure of a Console Application


Question: In your console application, you have a procedure called Main. What is its
purpose?
Answer: The Main procedure provides an entry point into or starting point for the console
application.

Performing Input and Output by Using a Console Application


Question: Which two methods would you use to do the following:

Display the message "Please press any key" on a new line.

Capture the key that the user pressed.

Answer: The correct answer is:


Console.WriteLine("Please press any key")
Dim keyPressed As ConsoleKeyInfo = Console.ReadKey()

Techniques for Commenting Visual Basic Applications


Question: Why is it important for you to comment your code?
Answer: Answers should include:

To improve the readability of your code.

To capture the rationale behind your logic.

To explain the purpose of elements in your code.

1-11

1-12

Programming in Visual Basic with Microsoft Visual Studio 2010

Additional Reading
Structure of a Console Application
For more information the Main procedure, see Main Procedure in Visual Basic.

Performing Input and Output by Using a Console Application


For more information about the Console class, see Console Class.

Programming in Visual Basic with Microsoft Visual Studio 2010

1-13

Lesson 4

Building a Graphical Application


Contents:
Question and Answers

Additional Reading

Detailed Demonstration Reading

1-14

Programming in Visual Basic with Microsoft Visual Studio 2010

Question and Answers


What Is Windows Presentation Foundation?
Question: What are some of the advantages of using WPF instead of Windows Forms?
Answer: WPF enables you to create applications with much more compelling user interfaces,
and offers greater control over user interface components.

Structure of a WPF Application


Question: Can you think of any other markup languages that like XAML?
Answer: Web applications that use HTML.

WPF Control Library


Question: You are building a simple form to capture user credentials and enable users to log
on. Which controls could you use to build this form?
Answer: Answers could include:

For layout, use a Grid control.

For labels for the user name and password, use Label controls.

For input boxes for the user name and password, use TextBox controls.

For a Submit button, use a Button control.

WPF Events
Question: When you develop your WPF applications, how do you specify events for
controls?
Answer: Declaratively by using XAML markup, or imperatively in Visual Basic code.

Building a Simple WPF Application


Question: What windows in Visual Studio 2010 do you typically use when you are building
your applications?
Answer: Answers should include:

Solution Explorer

Properties

XAML

Design

Code Editor

Demonstration: Building a Simple WPF Application


Question: When you are developing a WPF application in Visual Studio 2010, what are the
two main ways in which you can set properties for WPF controls?
Answer: You can set properties by using the Properties window, or by editing the XAML for the control
directly by using the XAML window.

Programming in Visual Basic with Microsoft Visual Studio 2010

Additional Reading
What Is Windows Presentation Foundation?
For more information about what WPF is, visit Introduction to WPF.

WPF Control Library


For more information about the controls in the WPF control library, see Control Library.

WPF Events
For more information about how WPF handles events, see Events (WPF).

1-15

1-16

Programming in Visual Basic with Microsoft Visual Studio 2010

Detailed Demonstration Steps


Demonstration: Building a Simple WPF Application
Detailed demonstration steps
Task 1: Create a new WPF application
1.

On the Start menu, point to All Programs, click Microsoft Visual Studio 2010, and then click
Microsoft Visual Studio 2010.

2.

In Visual Studio 2010, on the File menu, click New Project.

3.

In the New Project dialog box, perform the following tasks, and then click OK:

a)

In the center pane, click WPF Application.

b)

In the Name box, type MyFirstWpfApp

c)

In the Location box, type D:\Demofiles\Mod1\Demo2\Starter

Task 2: Add controls to the WPF application


1.

On the View menu, click Toolbox.

2.

In the Toolbox window, double-click Button.

3.

Show students the control in the Design window, and the XAML markup in the XAML window.

Task 3: Set the properties for the controls


1.

In the Design window, click the Button control.

2.

In the Properties window, on the Properties tab, set the following properties:

Name: ClickMeButton

FontSize: 20

Height: 50

Width: 150

3.

In the XAML window, perform the following:

In the Button element, set the Content attribute to Click Me.

In the Window element, set the Height attribute to 150.

In the Window element, set the Width attribute to 190.

Task 4: Add code to the application


1.

In the Design window, click the Button control.

2.

In the Properties window, on the Events tab, show students the different types of events that you
can handle for a Button control, and then double-click Click.

3.

In the Code Editor window for the MainWindow.xaml.vb file, in the ClickMeButton_Click
method, add the code in the following code example.

...
Private Sub ClickMeButton_Click(ByVal sender As System.Object, ByVal e As
System.Windows.RoutedEventArgs) Handles ClickMeButton.Click

Programming in Visual Basic with Microsoft Visual Studio 2010

1-17

MessageBox.Show("You clicked me!!")


End Sub
...

4.

Explain to students that you have just added code so that, when the button is clicked, a message
box is displayed.

Task 5: Build and run the application


1.

On the Build menu, click Build Solution.

2.

On the Debug menu, click Start Debugging.

3.

In the MainWindow window, click Click Me, and then click OK.

4.

On the Debug menu, click Stop Debugging.

1-18

Programming in Visual Basic with Microsoft Visual Studio 2010

Lesson 5

Documenting an Application
Contents:
Question and Answers

Additional Reading

Programming in Visual Basic with Microsoft Visual Studio 2010

Question and Answers


What Are XML Comments?
Question: Why should you use XML comments rather than standard comments?
Answer: XML comments enable you to define comments in a more structured way. You can
extract XML by using tools such as Sandcastle Help File Builder.

Common XML Comment Tags


Question: Which tag would you use to provide a detailed description of a method?
Answer: The <remarks> tag.

Generating Documentation from XML Comments


Question: Which switch do you need to provide to get vbc.exe to produce XML output?
Answer: The /doc switch.

1-19

1-20

Programming in Visual Basic with Microsoft Visual Studio 2010

Additional Reading
What Are XML Comments?
For more information about XML comments, see Documenting Your Code with XML (Visual
Basic).

Common XML Comment Tags


For more information about XML comment tags, see Recommended XML Tags for
Documentation Comments (Visual Basic).

Generating Documentation from XML Comments


For more information about Sandcastle Help File Builder, see Sandcastle Help File Builder.

Programming in Visual Basic with Microsoft Visual Studio 2010

1-21

Lesson 6

Debugging Applications by Using Visual Studio 2010


Contents:
Question and Answers

1-22

Programming in Visual Basic with Microsoft Visual Studio 2010

Question and Answers


Debugging in Visual Studio 2010
Question: What are some of the debug functions that Visual Studio 2010 provides?
Answer: Answers should include:

Start/stop debugging.

Halt on a breakpoint.

Using Breakpoints
Question: How would you use the debug functions in Visual Studio 2010 to debug your
application and pause on a specific line of code?
Answer: Answers should include:
1.

Locate the line of interest and set a breakpoint.

2.

Start the application with debugging.

Stepping Through Code


Question: Why would you use the Step into and Step over debug functions?
Answer: Answers should include:

You would use Step into if you wanted to investigate the behavior in a particular method.

You would use Step over if you didnt want to investigate the behavior of a method, but wanted
to skip to the next line.

Using Debug Windows


Question: Why would you use the Locals and Immediate windows when developing your
application?
Answer: Answers should include:

You would use the Locals window to view and edit local (in-scope) variables.

You would use the Immediate window to evaluate expressions, execute statements, and print out
variable values.

Programming in Visual Basic with Microsoft Visual Studio 2010

1-23

Module Reviews and Takeaways


Review questions
Question: What is the purpose of the .NET Framework and the role of Visual Basic?
Answer: The .NET Framework 4 provides a comprehensive development platform that offers
a fast and efficient way to build applications and services. Visual Basic is the language of
choice for many developers. It uses an English-language like syntax, somewhat similar to that
of Pascal, and has several extensions and features that are designed for operation with the
.NET Framework.
Question: What is the purpose of Visual Studio 2010 templates?
Answer: Visual Studio 2010 supports the development of different types of applications such
as Windows-based client applications, Web-based applications, services, and libraries. To
help you get started, Visual Studio 2010 provides several application templates that provide
a structure for the different types of applications.
Question: What is the purpose of Visual Studio projects and solutions?
Answer: A project is used to organize source files, references, and project-level configuration
settings that make up a single .NET Framework application or library. A single Visual Studio
solution is a container for one or more projects.
Question: What is the purpose of a Main procedure or method?
Answer: Every Visual Basic application that compiles into an executable file must have a
Main procedure method. This method provides the CLR with an entry point into or starting
point for the application. When you run a .NET Framework application, the Main procedure
or method is the first method that the CLR executes.
Question: List some of the controls that WPF provides.
Answer: Any of Button, Canvas, ComboBox, Grid, Label, StackPanel, and TextBox.
Question: What is the purpose of XML comments?
Answer: In Visual Studio 2010, you can add comments to your source code that will be
processed to an XML file. This file can then be the input to a process that creates Help
documentation for the classes in your code.
Question: What is the purpose of the Visual Studio 2010 debugger?
Answer: Debugging is an essential part of application development. You may notice errors
as you write code, but some errorsespecially logic errorsmay only occur in specific
circumstances that you do not test for. Users may report these errors to you, and you will
have to correct them. Visual Studio 2010 provides several tools to help you debug code.

Best Practices
Help the students understand the best practices presented in this section. Ask students to
consider these best practices in the context of their own business situations:

Keep the Main procedure or method small and lightweight.

Declare variables by using meaningful names and avoid reference to the underlying data type,
such as nameString.

1-24

Programming in Visual Basic with Microsoft Visual Studio 2010

Define controls by using meaningful names and suffix using the underlying control type, such as
NameLabel.

Add comments to your code that describe your ideas.

Programming in Visual Basic with Microsoft Visual Studio 2010

1-25

Tools
Tool

Use to

Where to find it

Gacutil.exe

Enables users to manipulate the


assemblies in the GAC. This can
include installing and
uninstalling assemblies in the
GAC so that multiple
applications can access them.

C:\Program Files
\Microsoft SDKs\Windows
\v7.0A\bin

Ildasm.exe

Enables users to manipulate


assemblies, such as determining
whether an assembly is
managed, or disassembling an
assembly to view the compiled
MSIL code.

C:\Program Files
\Microsoft SDKs\Windows
\v7.0A\bin

Makecert.exe

Enables users to create x.509


certificates for use in their
development environment.
Typically, you can use these
certificates to sign your
assemblies and define SSL
connections.

C:\Program Files
\Microsoft SDKs\Windows
\v7.0A\bin

Ngen.exe

Enables users to improve the


performance of .NET
applications. The Native Image
Generator improves
performance by precompiling
assemblies into images that
contain processor-specific
machine code. The CLR can then
run the precompiled images
instead of using JIT compilation.

C:\Windows\Microsoft.NET
\Framework\v4.0.30319

Sn.exe

Enables users to sign assemblies


with strong names. The Strong
Name Tool includes commands
to create a new key pair, extract
a public key from a key pair, and
verify assemblies.

C:\Program Files
\Microsoft SDKs\Windows
\v7.0A\bin

1-26

Programming in Visual Basic with Microsoft Visual Studio 2010

Lab Review Questions and Answers


Question: Which methods did you use to capture and display information in your console
application?
Answer: The Shared ReadLine and WriteLine methods.
Question: Which event did you handle on the Format Data button in your WPF application?
Answer: The Click event handler.
Question: Which debugging functions did you use when you verified the application?
Answer: Start Debugging, breakpoint, Step into, Step over, and the Immediate window.
Question: How do you instruct Visual Studio 2010 to produce an XML file that contains XML
comments?
Answer: Set the XML documentation file property.

Programming in Visual Basic with Microsoft Visual Studio 2010

2-1

Module 2
Introducing Visual Basic and the .NET Framework
Contents:
Lesson 1: Declaring Variables and Assigning Values

Lesson 2: Using Expressions and Operators

Lesson 3: Creating and Using Arrays

Lesson 4: Using Decision Statements

11

Lesson 5: Using Iteration Statements

14

Module Reviews and Takeaways

17

Lab Review Questions and Answers

18

2-2

Programming in Visual Basic with Microsoft Visual Studio 2010

Lesson 1

Declaring Variables and Assigning Values


Contents:
Question and Answers

Additional Reading

Programming in Visual Basic with Microsoft Visual Studio 2010

2-3

Question and Answers


What Are Variables?
Question: What is a variable and how are variables used in Microsoft .NET Framework
applications?
Answer: Variables store values that the application requires, in temporary memory locations.
Applications process these values to perform functions such as calculations, data analysis,
and database interactions.

What Are Data Types?


Question: What type would you use to store a sequence of alphanumeric characters?
Answer: A String type.

Declaring and Assigning Variables


Question: What is the syntax for declaring and assigning a variable?
Answer: One possible answer is: Dim variableName As DataType = Value

What Is Variable Scope?


Question: You are developing an application and you need to declare a variable that is
accessible to two methods in the same class. What is the easiest way to achieve this?
Answer: Use class scope and declare a private field at the class level.

Converting a Value to a Different Data Type


Question: You are converting a String to an Integer type, but you are unsure whether the
String will contain a valid Integer value. Which conversion approach should you use?
Answer: You should use the Integer.TryParse method.

Read-Only Variables and Constants


Question: What are the main differences between a constant and a read-only variable?
Answer: Answers should include the following:

The declaration, Const statement and ReadOnly keyword.

Constants can only be initialized at compile time, whereas you can initialize a read-only variable
at run time.

You can initialize a read-only variable at its declaration or in the class constructor, whereas you
can only initialize a constant at its declaration.

2-4

Programming in Visual Basic with Microsoft Visual Studio 2010

Additional Reading
What Are Data Types?
For more information about the Option Strict compiler switch, see Option Strict Statement.
For more information about late binding, see Early and Late Binding (Visual Basic).

Declaring and Assigning Variables


For more information about the keyword in Visual Basic, see Visual Basic Keywords.
For more information about naming conventions, see General Naming Conventions.
For more information about capitalization conventions, see Capitalization Conventions.
For more information about the Option Explicit compiler switch, see Option Explicit Statement.

What Is Variable Scope?


For more information about scopes, see Scope in Visual Basic.

Converting a Value to a Different Data Type


For more information about the CType function, see CType Function (Visual Basic).
For more information about the System.Convert class, see Convert Class.
For more information about the type conversion functions, see Type Conversion Functions.

Read-Only Variables and Constants


For more information about constants, see ReadOnly (Visual Basic).
For more information about constants, see Const Statement (Visual Basic).

Programming in Visual Basic with Microsoft Visual Studio 2010

2-5

Lesson 2

Using Expressions and Operators


Contents:
Question and Answers

Additional Reading

2-6

Programming in Visual Basic with Microsoft Visual Studio 2010

Question and Answers


What Is an Expression?
Question: What is the value of the expression "99" + "1"?
Answer: The string, "991".

What Are Operators?


Question: Which operator would you use to calculate the remainder after dividing one
integer value by another?
Answer: The Mod operator.

Specifying Operator Precedence


Question: How can you control the order of processing in an expression?
Answer: Use parentheses to override the precedence of operators. Expressions in the
parentheses are evaluated first.

Best Practices for Performing String Concatenation


Question: Why is concatenating strings considered bad practice, and how can you avoid it?
Answer: Concatenating strings is considered bad practice because strings are immutable.
This means that every time you concatenate a string, you create a new string in memory. To
avoid this problem, concatenate strings by using the StringBuilder class.

Programming in Visual Basic with Microsoft Visual Studio 2010

Additional Reading
What Are Operators?
For more information about the operators in Visual Basic, see Operators (Visual Basic).

Best Practices for Performing String Concatenation


For more information about the StringBuilder class, see StringBuilder Class.

2-7

2-8

Programming in Visual Basic with Microsoft Visual Studio 2010

Lesson 3

Creating and Using Arrays


Contents:
Question and Answers
Additional Reading

9
10

Programming in Visual Basic with Microsoft Visual Studio 2010

Question and Answers


What Is an Array?
Question: What is an array, and why would you want to use arrays in a Visual Basic
application?
Answer: An array is a set of elements that are grouped together and managed as a unit.
Arrays enable you to handle a set of closely related data.

Creating and Initializing Arrays


Question: How do you declare a multidimensional array?
Answer: Answers should resemble the following code example.
Dim arrayName(Size1, Size2) As Type

Common Properties and Methods Exposed by Arrays


Question: What members would you use to locate the last element in an array and then
change that elements value?
Answer: Use the following code example to illustrate the answer.
Dim oldNumbers() As Integer = { 1, 2, 3, 4, 5 }
oldNumbers.SetValue(5000, oldNumbers.Length -1)

Accessing Data in an Array


Question: Explain two approaches to accessing data in an array.
Answer: Answers should include two of the following:

Indexer

GetValue

Explicit GetEnumerator

Implicit GetEnumerator

2-9

2-10

Programming in Visual Basic with Microsoft Visual Studio 2010

Additional Reading
Creating and Initializing Arrays
For more information the Main procedure, see Main Procedure in Visual Basic.

Common Properties and Methods Exposed by Arrays


For more information about the System.Array class, see the Array Class.

Programming in Visual Basic with Microsoft Visual Studio 2010

2-11

Lesson 4

Using Decision Statements


Contents:
Question and Answers

12

Additional Reading

13

2-12

Programming in Visual Basic with Microsoft Visual Studio 2010

Question and Answers


Using One-Way If Statements
Question: When must you close an If statement with a matching End If statement?
Answer: You must close an If statement with a matching End If statement, if you split the If
statement across two or more lines of code. It is also good practice even if you only use a
single statement because you may need to add additional statements later.

Using Either-Or If Statements


Question: Think of a scenario where you may want to use the If Then Else statement and
discuss.
Answer: This question is designed to stimulate discussion among the students, so there is no
definitive answer. However, one possible answer can be to prompt a user for input and test
whether the input is valid. If it is valid, process the input; if it is invalid, display an error
message.

Using Multiple-Outcome If Statements


Question: What is the purpose of the Else statement in an Else If construct?
Answer: The Else statement is the default block and should contain logic that will be
executed if none of the conditions in the previous If and Else If conditions return False.

Using the Select Case Statement


Question: With the exception of the default case, is the order of the cases in a Select Case
statement important?
Answer: No. You cannot fall through from one case to another, so the order in which they
occur is immaterial.

Guidelines for Choosing a Decision Construct


Question: Which statement would you use to perform an action based on the possible
values of a single variable?
Answer: The Select Case statement.

Programming in Visual Basic with Microsoft Visual Studio 2010

Additional Reading
Using Either-Or If Statements
For more information about the If operator, see If Operator (Visual Basic).

2-13

2-14

Programming in Visual Basic with Microsoft Visual Studio 2010

Lesson 5

Using Iteration Statements


Contents:
Question and Answers

15

Additional Reading

16

Programming in Visual Basic with Microsoft Visual Studio 2010

Question and Answers


Types of Iteration Statements
Question: Which iteration statement would you use to prompt a user for a valid response?
Answer: The most suitable loop for this scenario is the Do Loop loop, although there are
many alternative solutions. Get students to justify their answers.

Using the While Loop


Question: When using the While loop, what type must the condition expression evaluate to?
Answer: The [condition] can be any expression that evaluates to a Boolean value.

Using the Do Loop


Question: What is the minimum number of iterations that a Do Loop will perform?
Answer: One, because the condition is evaluated at the end of the loop.

Using the For Loop


Question: What are the four components of a For loop?
Answer: Answers should include the following:

A numeric variable to use for the counter (this can be a variable that is already defined or a
variable that was defined as part of the loop specification).

A starting value for the counter variable.

A limit for the counter variable.

Instructions for how to modify the counter variable at the end of each iteration.

Exit and Continue Statements


Question: What is the difference between the Exit and Continue statements?
Answer: The Exit statement enables you to exit the loop entirely, and skip to the next line of
code outside the loop. The Continue statement is similar to the Exit statement, except that,
instead of exiting the loop entirely, you simply skip the remaining code in the current
iteration, test the condition, and then start the next iteration of the loop.

2-15

2-16

Programming in Visual Basic with Microsoft Visual Studio 2010

Additional Reading
Types of Iteration Statements
For more information about the While...End While statement, see While...End While Statement
(Visual Basic).
For more information about the Do...Loop statement, see Do...Loop Statement (Visual Basic).
For more information about the For...Next statement, see For...Next Statement (Visual Basic).

Programming in Visual Basic with Microsoft Visual Studio 2010

2-17

Module Reviews and Takeaways


Review questions
Question: If you omit the type when declaring a variable, what does it mean?
Answer: It means that it is an implicit variable where the data type is inferred by the
initializers value. (This is the default behavior, but it depends on the compiler settings.)
Question: How can you control the order of processing in an expression?
Answer: You can use parentheses to control the order of processing in an expression.
Question: What is the purpose of arrays?
Answer: An array is used for any number of objects that you can group together and
manage as a unit.
Question: Name an alternative approach to using the If Else statements.
Answer: Using either the Select Case statement or the If operator.
Question: Which loop construct should you use to run a block of code one or more times?
Answer: The Do loop.

Best Practices
Best Practices Related to Using Visual Basic Constructs
Help the students understand the best practices presented in this section. Ask students to
consider these best practices in the context of their own business situations:

When you choose a data type, ensure that you select one that is appropriate to the type of data
that you are processing. For example, do not create a Double variable for processing integer data
because this requires that the compiler generates additional code to convert your integer data
into Double values.

Instead of concatenating strings by using the & operator, use the StringBuilder class, or use the
static Format method of the String class..

When you access elements in an array by using the index of an element, ensure that you test to
see whether the index exists. If the index does not exist, you will get an IndexOutOfRange
exception.

Avoid too many nested If Else and loop statements because they can complicate debugging
your applications.

Avoid using Exit and Continue statements in loops, unless you really need them.

2-18

Programming in Visual Basic with Microsoft Visual Studio 2010

Lab Review Questions and Answers


Question: Which .NET Framework class and method did you use to calculate the square
root?
Answer: The Math class and the Sqrt method.
Question: Which .NET Framework class did you use to construct the string that represented
the binary number, and what benefits does this class provide?
Answer: The StringBuilder class, which enables you to dynamically build a string without the
overhead of concatenating several string variables.
Question: Which loop construct did you use to iterate through all the rows in the matrix1
array, and why was it a good choice?
Answer: I used the For loop. This was a good choice because I knew how many rows were in
the array.

Programming in Visual Basic with Microsoft Visual Studio 2010

3-1

Module 3
Declaring and Calling Methods
Contents:
Lesson 1: Defining and Invoking Methods

Lesson 2: Specifying Optional Parameters and ByRef Parameters

Module Reviews and Takeaways

12

Lab Review Questions and Answers

13

3-2

Programming in Visual Basic with Microsoft Visual Studio 2010

Lesson 1

Defining and Invoking Methods


Contents:
Question and Answers

Additional Reading

Detailed Demonstration Steps

Programming in Visual Basic with Microsoft Visual Studio 2010

Question and Answers


What Is a Method?
Question: Why do you need to use methods when developing a .NET Framework application
with Visual Basic?
Answer: All code must belong to a method. If you dont define methods, you cannot
implement behavior. In addition, all Visual Basic programs must have at least one method
called Main, which defines the starting point for the application.

Creating a Method
Question: What are the four elements in the method specification?
Answer: The four elements are:

Access modifier

Return type

Method name

Parameter list

Calling a Method
Question: How can you call the method in the following code example?
Sub DeleteReport(ByVal reportName As String)
Answer: Answers should resemble the following code example. Users should specify the
method name and a string parameter, and there is no return value.
DeleteReport("MyReport")

Creating and Calling Overloaded Methods


Question: What is meant by overloading a method?
Answer: Overloading is the ability to define several methods with the same name in the
same class, provided each method has a different signature.

Using Parameter Arrays


Question: How do you define a method that takes a parameter array?
Answer: You need to do the following:

The parameter array must be the last parameter in the parameter list.

You must prefix the parameter with the ParamArray keyword.

The parameter must be an array.

Refactoring Code into a Method


Question: Why would you want to refactor code into a method?
Answer: When you need to perform the same logic several times in different places.

3-3

3-4

Programming in Visual Basic with Microsoft Visual Studio 2010

Testing a Method
Question: Why would you want to use unit tests when developing your .NET Framework
applications?
Answer: Unit tests provide an excellent way to help simplify the testing process and ensure
that your tests are reliable and easily repeatable.

Demonstration: Refactoring and Testing a Method


Question: Name one way in which you can view and start your unit tests.
Answer: Answers can include:

In the Test View window.

In the Test Results window.

On the Test menu.

Programming in Visual Basic with Microsoft Visual Studio 2010

Additional Reading
Creating a Method
For more information about procedures or methods, see Procedures in Visual Basic.

Creating and Calling Overloaded Methods


For more information about method overloading, see Procedure Overloading (Visual Basic).

Using Parameter Arrays


For more information about parameter arrays, see Parameter Arrays (Visual Basic).

3-5

3-6

Programming in Visual Basic with Microsoft Visual Studio 2010

Detailed Demonstration Steps


Demonstration: Refactoring and Testing a Method
Detailed demonstration steps
Task 1: Open the existing application and view the existing code
1.

Click Start, point to All Programs, click Microsoft Visual Studio 2010, and then click Microsoft
Visual Studio 2010.

1.

In Visual Studio 2010, on the File menu, click Open Project.

2.

In the Open Project dialog box, browse to the D:\Demofiles\Mod3\Demo1\Starter folder, and
then double-click MethodRefactorAndTestDemo.sln.

3.

In Solution Explorer, in the MethodRefactorAndTestDemo project, right-click the Module1.vb


file, and then click View Code.

4.

Explain that the Main method includes some code to generate an array of random numbers
based on the following three constraints:

5.

Minimum number for any of the random numbers.

6.

Maximum number for any of the random numbers.

7.

Number of random numbers required.

8.

Explain that you want to use this code elsewhere in your application, so you are going to refactor
it into a new method.

Task 2: Refactor an existing code block


1.

In the Code Editor window, in the Main method, select all the code.

2.

Right-click the selected code block, and then click Cut.

3.

Below the Main method, create a new Function named GenerateRandomNumbers, and paste
in the copied code.

Private
Dim
Dim
Dim

Function GenerateRandomNumbers() As Integer()


min As Integer = 48
max As Integer = 50
numberOfRequirednumbers As Integer = 100

Dim randomNumbers() As Integer


ReDim randomNumbers(numberOfRequirednumbers)
Dim numberGenerator As New Random()
For count As Integer = 0 To numberOfRequirednumbers - 1
randomNumbers(count) = numberGenerator.Next(min, max)
Next
' More logic that use the randomNumbers variable.
Array.Sort(randomNumbers)
End Function

Task 3: Add parameters and call the GenerateRandomNumbers method


1.

Move the local min, max, and numberOfRequirednumbers variables up to be parameters.

Programming in Visual Basic with Microsoft Visual Studio 2010

3-7

Public Function GenerateRandomNumbers(ByVal min As Integer, ByVal max As Integer,


ByVal numberOfRequirednumbers As Integer) As Integer()
Dim randomNumbers() As Integer
...

2.

Return the randomNumbers array as the last action in the GenerateRandomNumbers method.

...
Return randomNumbers
End Function

3.

Call the GenerateRandomNumbers method from the Main method, and save the return value
in an integer array named randomNumbers.

Sub Main()
Dim randomNumbers() As Integer = GenerateRandomNumbers(48, 50, 100)
End Sub

Task 4: Generate a unit test for the GenerateRandomNumbers method


1.

In the Code Editor window, right-click the GenerateRandomNumbers method, and then click
Create Unit Tests.

2.

In the Create Unit Tests dialog box, perform the following, and then click OK.

3.

a)

In the Current selection list, show students the available components in the project.

b)

In the Output project list, explain that if the solution already contained a test project, you
could select it here.

c)

Click Settings.

d)

In the Test Generation Settings dialog box, clear the Honor InternalsVisibleTo Attribute
check box, and then click OK.

In the New Test Project dialog box, click Create.


Note: If the Add InternalsVisibleTo Attribute dialog box appears, click Yes.
Note: If the You have made changes to your tests dialog box appears, click OK.

Task 5: Examine the auto-generated unit test method


1.

In the Code Editor window, in the Module1Test class, navigate to the


GenerateRandomNumbersTest method.

2.

Show students the following:

The TestMethod() method attribute. Explain that all test methods are decorated with this
attribute.

The declaration of the min, max, and numberOfRequiredNumbers variables that the
GenerateRandomNumbers method requires.

The Assert.AreEqual statement to test the result that is returned from the
GenerateRandomNumbers method.

Task 6: Modify the auto-generated unit test method


1.

Make the following changes to the GenerateRandomNumbersTest method:

3-8

Programming in Visual Basic with Microsoft Visual Studio 2010

Set the max variable to 100.


Set the numberOfRequirednumbers variable to 998.
Remove the Dim expected() As Integer = Nothing ' TODO: Initialize to an appropriate
value line.
Replace the Assert.AreEqual(expected, actual) line with Assert.AreEqual(1000,
actual.Length)
Remove the Assert.Inconclusive("Verify the correctness of this test method.") line.
Your code should resemble the following code example.
Public Sub GenerateRandomNumbersTest()
Dim min As Integer = 0
Dim max As Integer = 100
Dim numberOfRequirednumbers As Integer = 998
Dim actual() As Integer
actual = Module1_Accessor.GenerateRandomNumbers(min, max,
numberOfRequirednumbers)
Assert.AreEqual(1000, actual.Length)
End Sub

2.

On the Build menu, click Build Solution.

Task 7: Run the unit test


1.

On the Test menu, point to Windows, and then click Test View.

2.

In the Test View window, right-click the GenerateRandomNumbersTest row, and then click Run
Selection.

3.

Show students the Test Results window, and that the unit test failed for the following reason:

Failed GenerateRandomNumbersTest
Expected:<1000>. Actual:<999>.

TestProject1

Assert.AreEqual failed.

4.

In the Code Editor window, navigate to the GenerateRandomNumbersTest method, and then
set the numberOfRequirednumbers variable to 999.

5.

In the Test View window, right-click the GenerateRandomNumbersTest row, and then click Run
Selection.

6.

Show students the Test Results window, and that the unit test succeeded.

Programming in Visual Basic with Microsoft Visual Studio 2010

3-9

Lesson 2

Specifying Optional Parameters and ByRef Parameters


Contents:
Question and Answers

10

Additional Reading

11

3-10

Programming in Visual Basic with Microsoft Visual Studio 2010

Question and Answers


What Are Optional Parameters?
Question: When defining a method with optional parameters, in what order must you
specify the parameters?
Answer: You must specify all mandatory parameters before optional parameters.

Calling a Method by Using Named Arguments


Question: What is the syntax for using named parameters in method calls?
Answer: methodName(parameterName1:= value1, parameterName2:=value2)

Programming in Visual Basic with Microsoft Visual Studio 2010

Additional Reading
What Are Optional Parameters?
For more information about optional parameters, see Optional Arguments (Visual Basic).

What Are ByRef Parameters?


For more information about ByRef parameters, see Passing Arguments by Value and by
Reference (Visual Basic).

3-11

3-12

Programming in Visual Basic with Microsoft Visual Studio 2010

Module Reviews and Takeaways


Review questions
Question: Which type of procedure or method does not return any data?
Answer: A Sub procedure or method.
Question: What term is given to the process of defining multiple methods with the same
name, but different parameter lists?
Answer: Method overloading.
Question: What is the difference between an optional parameter and a named argument?
Answer: An optional parameter is part of a method signature, and specifies that a parameter
has a default value. When an application invokes the method, it can omit the argument that
corresponds to this parameter and the method will use the default value instead.
A named argument is the syntax that an application can use when it invokes a method. An
application can specify the arguments in any order by prefixing them with the name of the
parameter that they should be used for.
Question: What is the purpose of ByRef parameters?
Answer: ByRef parameters enable you to return multiple values from a method.
Best Practices Related to Using Methods
Help the students understand the best practices presented in this section. Ask students to
consider these best practices in the context of their own business situations.

Best Practices
Best Practices Related to Using Methods
Help the students understand the best practices presented in this section. Ask students to
consider these best practices in the context of their own business situations.

Keep methods as small and lightweight functional units. If methods start to become large,
consider refactoring code into smaller logical methods.

Create unit tests for all Public methods. You can assume that any Private methods that you
create will be tested when the Public methods are called.

Use ByRef parameters only when it is absolutely necessary. If you find yourself using ByRef
parameters too often, reconsider the purpose of the method.

Programming in Visual Basic with Microsoft Visual Studio 2010

Lab Review Questions and Answers


Question: When using ByRef parameters in a method, what happens when you pass a
specific value and not a variable when calling the method?
Answer: Any new value assigned to the ByRef parameter is discarded when the method call
completes.
Question: When adding optional parameters to an existing method signature, why will your
code run successfully without making changes to any of the existing method calls?
Answer: When you add optional parameters, you provide default values. If you do not
explicitly set the optional parameters in your method calls, the default parameters will be
used.
Question: When creating a unit test method in a Visual Studio test project, what attribute
must you decorate your test method with?
Answer: The TestMethod attribute.

3-13

Programming in Visual Basic with Microsoft Visual Studio 2010

Module 4
Handling Exceptions
Contents:
Lesson 1: Handling Exceptions

Lesson 2: Raising Exceptions

Module Reviews and Takeaways

Lab Review Questions and Answers

10

4-1

4-2

Programming in Visual Basic with Microsoft Visual Studio 2010

Lesson 1

Handling Exceptions
Contents:
Question and Answers

Additional Reading

Detailed Demo Steps

Programming in Visual Basic with Microsoft Visual Studio 2010

Question and Answers


What is an Exception?
Question: Discuss your experiences of applications that have crashed, with other students
and the instructor.
Answer: This question is designed to stimulate discussion among the students, so there is no
definitive answer. Students should think about all the applications that they have used that
have performed unexpectedly or crashed. You can then point out that the developer failed
to handle such conditions.

Using a Try/Catch Block


Question: How would you use the Try/Catch block to catch all exceptions regardless of
type, and then run some generic additional logic?
Answer: To catch all exceptions, you could use the code in the following code example.
Try

' Your logic.


Catch
' Logic to execute in the event of an exception.
End Try

Using Exception Properties


Question: You have a Catch block that contains some logic to write details of any exceptions
to a log file. The Catch block will catch all types of exceptions. What members of the
exception class would you use to get a description and the source of the error?
Answer: The Message and Source properties.

Using a Finally Block


Question: Describe the difference between a Catch block and a Finally block.
Answer: A Catch block contains code that runs only when a matching exception is thrown. A
Finally block contains code that always runs, regardless of whether an exception is thrown.

Demonstration: Raising Exceptions in Visual Studio


Question: How can you guarantee that Visual Studio will always notify you if an exception
occurs, instead of automatically propagating the exception to a Catch block?
Answer: You can use the Exceptions dialog box to configure the exception as Thrown,
instead of User-Handled.

4-3

4-4

Programming in Visual Basic with Microsoft Visual Studio 2010

Additional Reading
Using a Try/Catch Block
For more information about Try/Catch blocks, see the Try...Catch...Finally Statement (Visual Basic) page.

Using Exception Properties


For more information about the members in the System.Exception class, see the Exception Members
page.

Programming in Visual Basic with Microsoft Visual Studio 2010

4-5

Detailed Demonstration Steps


Demonstration: Raising Exceptions in Visual Studio
Detailed demonstration steps
Task 1: Open the existing application and view the existing code.
1.

Click Start, point to All Programs, click Microsoft Visual Studio 2010, and then click Microsoft
Visual Studio 2010.

2.

In Visual Studio 2010, on the File menu, click Open Project.

3.

In the Open Project dialog box, browse to the D:\Demofiles\Mod4\Demo1\Starter folder,


and then double-click FabrikamUserManagement.sln.

4.

Open the Module1.vb code file.

5.

In the Code Editor window, point to the Main method and explain the following:
a.

The Main method contains a call to the Users.GetUserById method, which returns a
user object for the provided user ID.

b.

If you specify a user ID that does not exist, the method returns Nothing.

c.

When the method returns, the application displays the userName field returned.

d.

The method call is in a Try/Catch block.

e.

The Catch block contains code to display details of any exceptions to the Command
Prompt window.

Task 2: Run the application and examine how it currently handles exceptions.
1.

On the Debug menu, click Start Debugging.

2.

Switch to the Command Prompt window, and show students the Object reference not set
to an instance of an object message.

3.

Explain that you got this message because a user could not be found with the ID of 5, so the
GetUserById method returned Nothing. Subsequently, any code that tries to use that user
object will generate a null reference exception.

4.

Explain that because the code is enclosed in a Try/Catch block, the exception was caught and
error logic was run.

5.

Explain that you can alter the performance of Visual Studio so that your code will stop
executing whenever an exception is thrown. Currently, Visual Studio is configured so that you
can catch exceptions and handle them yourself, such as with a Try/Catch block.

6.

On the Debug menu, click Stop Debugging.

Task 3: Modify the exception configuration in Visual Studio to always throw exceptions.
1.

On the Debug menu, click Exceptions.

2.

In the Exceptions dialog box, in the Break when an exception is list, expand Common
Language Runtime Exceptions, and then expand System.

3.

Explain that by using this list and the associated Thrown and User-unhandled check boxes,
you can control how Visual Studio notifies you when an exception is generated.

4-6

Programming in Visual Basic with Microsoft Visual Studio 2010

4.

Explain that the code in our application generated a null reference exception, so that is the
type of exception that we will modify.

5.

In the Break when an exception is list, under System, locate the


System.NullReferenceException row.

6.

For the System.NullReferenceException row, clear the User-unhandled check box, and
then select the Thrown check box.

7.

In the Exceptions dialog box, click OK.

Programming in Visual Basic with Microsoft Visual Studio 2010

Lesson 2

Raising Exceptions
Contents:
Question and Answers

4-7

4-8

Programming in Visual Basic with Microsoft Visual Studio 2010

Question and Answers


Creating an Exception Object
Question: You are in the process of adding several new methods to your application. So far,
you have added the method signatures. What else should you do to indicate that the
method is not complete and functional?
Answer: You should throw a NotImplementedException exception. Syntax for throwing an
exception is covered in the next topic.

Throwing an Exception
Question: Where does execution continue after you perform a Throw statement?
Answer: The next Catch block in the call stack.

Best Practices for Handling and Raising Exceptions


Question: In your application, you have a method that returns a user object. When you have
the user object, you are going to use it as a parameter in another method call. There is a
possibility that some of the data in the user object is incorrectly formatted, and if you try to
use this data, it would cause an exception. What would you do in this situation?
Answer: The point here is that you should not rely on exception handling for normal
processing. In this example, it would be best to test whether the data is in the correct format
before processing, rather than just hoping it works and does not throw an exception. Explain
that in some scenarios, this can be a tough decision.

Programming in Visual Basic with Microsoft Visual Studio 2010

4-9

Module Reviews and Takeaways


Review questions
Question: In your application, you have a method call that depends on many variables that
are out of the control of your application. It is very likely that this method call will throw an
exception. You have implemented a centralized exception-handling system so that all
exceptions are caught and handled in a single place. When you make the method call, if an
exception is thrown, you just want to ensure that you manage and close any resources.
Which construct would you use?
Answer: The Try/Finally construct
Question: In your application, you have defined several custom exception classes. You have
several Catch blocks that catch this type of exception. In your Catch blocks, you want to
wrap this type of exception in a more generic exception type. What constructor parameter
can you set to ensure that the more specific exception is included in the chain?
Answer: The InnerException parameter.
Question: What should you do with detailed exception messages?
Answer: Log them because they will help you diagnose problems in your application. Do not
display them to the user.

Best Practices
Help the students understand the best practices presented in this section. Ask students to consider these
best practices in the context of their own business situations.
Supplement or modify the following best practices for your own work situations:

Always design your applications with errors in mind. Users will always find ways to break your
application.

Design your exception handling such that all exceptions are handled in a centralized location.

Do not design your application to rely on exceptions to function normally.

Do not display detailed exception messages to the user because a malicious user could use detailed
technical information to make your application malfunction.

4-10

Programming in Visual Basic with Microsoft Visual Studio 2010

Lab Review Questions and Answers


Question: What construct did you use to make the method calls fail-safe?
Answer: The Try/Catch block.
Question: What attribute did you need to decorate the test method so that it expected an
exception?
Answer: The ExpectedException attribute, specifying the type of exception expected.

Programming in Visual Basic with Microsoft Visual Studio 2010

Module 5
Reading and Writing Files
Contents:
Lesson 1: Accessing the File System

Lesson 2: Reading and Writing Files by Using Stream

Module Reviews and Takeaways

Lab Review Questions and Answers

10

5-1

5-2

Programming in Visual Basic with Microsoft Visual Studio 2010

Lesson 1

Accessing the File System


Contents:
Question and Answers

Additional Reading

Programming in Visual Basic with Microsoft Visual Studio 2010

Question and Answers


Manipulating Files
Question: In your application, you use files as a temporary storage mechanism while the
application is running. When the application stops running, you want to make sure that the
file exists, and then delete the file. What is the easiest way to achieve this?
Answer: The easiest approach would be to use the static Exists and Delete methods of the
File class.

Reading from and Writing to Files


Question: In your application, you have just added some logic to handle exceptions. You
now want to extend this logic further to store details of these exceptions to a log file on the
file system so that you can diagnose any problems. You will be writing a string variable and
you should want to never overwrite any existing log records in a file. Which method would
you use?
Answer: The AppendAllText method.

Manipulating Directories
Question: What class would you use to retrieve an instance of a directory in the file system,
which you can then interact with?
Answer: You would create an instance of the DirectoryInfo class by using the default
constructor passing in the path to the directory.

Manipulating Paths
Question: You are creating a filter that enables users to browse files by extension. To start
with, you need to get the extensions of each file and then run some logic depending on the
result. You also want to display the file name, including the extension in a list. Which
methods would you use to query the files?
Answer: The GetExtension and GetFileName methods.

Using the My Namespace


Question: What is the full name of the object in the My namespace that can be used for
manipulating the file system?
Answer: The full name of the object in the My namespace that can be used for manipulating
the file system is My.Computer.FileSystem.

Using the Common File System Dialog Boxes


Question: You have almost completed your implementation of a text editor, and the final
step is to get users to browse to a save location, and prompt them for a file name. What class
would you use and how would you use it?
Answer: You would use the SaveFileDialog class in the following way:
1.

Create an instance of the SaveFileDialog class.

2.

Set any properties to customize its behavior.

5-3

5-4

Programming in Visual Basic with Microsoft Visual Studio 2010

3.

Call the ShowDialog method to show the dialog box.

4.

Use the result returned in the FileName property.

Programming in Visual Basic with Microsoft Visual Studio 2010

Additional Reading
Manipulating Files
For more information about the File class, see the File Class page.
For more information about the FileInfo class, see the FileInfo Class page.

Manipulating Directories
For more information about the Directory class, see the Directory Class page.
For more information about the DirectoryInfo class, see the DirectoryInfo Class page.

Manipulating Paths
For more information about the Path class, see the Path Class page.

Using the My Namespace


For more information about the My namespace, see the Development with My (Visual Basic) page.
For more information about the My.Application object, see the ApplicationBase Class page.
For more information about the My.Computer object, see the Computer Class page.
For more information about the My.User object, see the User Class page.

5-5

5-6

Programming in Visual Basic with Microsoft Visual Studio 2010

Lesson 2

Reading and Writing Files by Using Streams


Contents:
Question and Answers

Additional Reading

Programming in Visual Basic with Microsoft Visual Studio 2010

Question and Answers


What are Streams?
Question: What do you think are the benefits of streaming data?
Answer: Answers should include:

The ability to read and write large amounts of data without consuming resources
such as memory and network bandwidth.

Not needing to load the entire amount of data into memory.

Enabling your application to handle any amount of data, regardless of size.

Reading and Writing Binary Data


Question: Why is it important to close streams when you have finished using them?
Answer: To release any file handles, and flush data to the underlying streams.

Reading and Writing Text


Question: You want to write a series of strings to a text file, and add a line break after each
string. What is the easiest way to achieve this?
Answer: Write the string by using the WriteLine method of the StreamWriter class.

Reading and Writing Primitive Data Types


Question: What method would you use to read a 64-bit signed integer from a binary
stream?
Answer: The ReadInt64 method

5-7

5-8

Programming in Visual Basic with Microsoft Visual Studio 2010

Additional Reading
What are Streams?
For more information about the FileStream class, see the FileStream Class page.

Reading and Writing Text


For more information about the StreamWriter class, see the StreamWriter Class page.
For more information about the StreamReader class, see the StreamReader Class page.

Reading and Writing Primitive Data Types


For more information about the BinaryWriter class, see the BinaryWriter Class page.
For more information about the BinaryReader class, see the BinaryReader Class page.

Programming in Visual Basic with Microsoft Visual Studio 2010

5-9

Module Reviews and Takeaways


Review questions
Question: When you write data to a stream, name two methods that you can use to ensure
that any buffered data is written to the underlying data source.
Answer: You could call the Flush or Close methods.
Question: Which two classes does the .NET Framework provide that display a graphical
control that enables you to capture a save file and open file path from a user?
Answer: The SaveFileDialog and OpenFileDialog classes.
Question: Which stream class would you use to write textual data?
Answer: The StreamWriter class.

Best Practices Related to Reading and Writing Data on the File System
Supplement or modify the following best practices for your own work situations:

Always check to make sure that the file exists before you try to read from it or write to it.

Do not assume that the contents in the file are going to be correct. Remember that files are stored on
the file system, which users have access to. Users are more than capable of editing a file that they
should not edit. Always parse a file to ensure that it is valid, or be prepared to catch and handle an
appropriate exception.

When you use streams, always ensure that you close the stream after use to ensure that you release
any handles on the underlying data source.

It is easy to assume that you will have permissions to write and read files anywhere in the live
environment. Typically, this is not the case. Make sure that your development environment mirrors the live
environment.

5-10

Programming in Visual Basic with Microsoft Visual Studio 2010

Lab Review Questions and Answers


Question: Explain the purpose of the File.Load and File.Save static methods.
Answer: You call the File.Load method passing the file path as the parameter. The method
returns a string that contains the full contents of the file.
You call the File.Save method passing the file path and text content as parameters. The text
content parameter is stored in a file at the file path on the hard disk.
Question: You have a file that contains text. You want to read the file one character at a
time. Which method of the StreamReader class would you use?
Answer: The Read method.

Programming in Visual Basic with Microsoft Visual Studio 2010

Module 6
Creating New Types
Contents:
Lesson 1: Creating and Using Modules and Enumerations

Lesson 2: Creating and Using Classes

Lesson 3: Creating and Using Structures

Lesson 4: Comparing References to Values

Module Reviews and Takeaways

14

Lab Review Questions and Answers

15

6-1

6-2

Programming in Visual Basic with Microsoft Visual Studio 2010

Lesson 1

Creating and Using Modules and Enumerations


Contents:
Question and Answers

Additional Reading

Programming in Visual Basic with Microsoft Visual Studio 2010

Question and Answers


What are Enumerations?
Question: Discuss with other students and the instructor where and how you have used
enumerations before.
Answer: This question is designed to stimulate discussion among the students, so there is no
definitive answer.

Creating New Enum Types


Question: Does the following code example show a legal enumeration?
Enum Seasons As SByte
Spring = -3
Summer
Fall
Winter
End Enum

Answer: Yes. The signed byte type allows negative numbers. The value assigned to Spring is
3, Summer has the value 2, Fall has the value 1, and Winter has the value 0.

Initializing and Assigning Enum Variables


Question: Describe how to initialize an enumeration variable.
Answer: You should:

Specify the type of enumeration.

Specify the name of the instance.

Assign a value by using the = operator.

6-3

6-4

Programming in Visual Basic with Microsoft Visual Studio 2010

Additional Reading
Creating New Enum Types
For more information about enumerations, see the Enum Statement (Visual Basic) page.

Programming in Visual Basic with Microsoft Visual Studio 2010

Lesson 2

Creating and Using Classes


Contents:
Question and Answers

Additional Reading

6-5

6-6

Programming in Visual Basic with Microsoft Visual Studio 2010

Question and Answers


What Is a Class?
Question: Explain the difference between a class and an object.
Answer: A class is a blueprint that defines the characteristics of an object, such as the data
that the object can contain and the operations that the object can perform.
An object is an instance of a class. You can use a single class to create as many objects as
your application requires.

Adding Members to Classes


Question: What is the difference between a field and a method?
Answer: Fields hold data, whereas methods expose functionality.

Defining Constructors and Initializing an Object


Question: What happens if you do not define a default constructor for a class?
Answer: If you do not define any constructors, a default parameterless constructor will be
provided. If you define one or more constructors, a default parameterless constructor will not
be provided.

Creating Objects
Question: Which operator must you use when you initialize a class to create an instance of
that class?
Answer: The New operator.

Accessing Class Members


Question: Highlight the syntax errors in the following code example.
Dim myCar As New Car("Ford", "Black")
' Set a field to indicate the car's transmission.
myCar,isManual() = True
' Call a method to calculate the car's value.
Dim value As Double = myCar,CalculateValue

Answer: The following code example highlights the errors.


Dim myCar As New Car("Ford", "Black")
' Set a field to indicate the car's transmission.
myCar,isManual() = True
' Comma should be period, and no parentheses.
' Call a method to calculate the car's value.
Dim value As Double = myCar,CalculateValue ' Comma should be period.

Using Partial Classes and Partial Methods


Question: What happens if you define a partial method, but do not provide an
implementation of this method?
Answer: Your code will still compile and run, and you will be able to call the method.
However, because the method contains no implementation, it will not do anything.

Programming in Visual Basic with Microsoft Visual Studio 2010

6-7

Additional Reading
Defining Constructors and Initializing an Object
For more information about constructors, see the Using Constructors and Destructors page.

Using Partial Classes and Partial Methods


For more information about partial classes and methods, see the Partial (Visual Basic) or Partial Methods
(Visual Basic) page.

6-8

Programming in Visual Basic with Microsoft Visual Studio 2010

Lesson 3

Creating and Using Structures


Contents:
Question and Answers

Programming in Visual Basic with Microsoft Visual Studio 2010

Question and Answers


What are Structures?
Question: Is the following code legal?
Dim x As Integer = 99
Dim y As System.Int32 = x + 1

Answer: Yes. It is legal because the Integer type is an alias for the System.Int32 type.

Defining and Using a Structure


Question: What keyword do you use to declare a structure?
Answer: The Structure keyword.

6-9

6-10

Programming in Visual Basic with Microsoft Visual Studio 2010

Lesson 4

Comparing References to Values


Contents:
Question and Answers

11

Additional Reading

13

Programming in Visual Basic with Microsoft Visual Studio 2010

Question and Answers


Comparing References Types to Value Types
Question: If Residence is a class (a reference type), what message does the following code
example display?
Dim myHouse As New Residence(ResidenceType.House, 2)
Dim anotherHouse As New Residence(ResidenceType.House, 2)
If myHouse Is anotherHouse Then
Console.WriteLine("They are the same house")
Else
Console.WriteLine("They are different houses")
End If

Answer: The message, They are different houses is displayed because they are different
objects, although both are of type Residence. If the Residence type was a Structure, the
code would not compile unless the Residence definition included an implementation for the
= operator, and subsequently also the <> operator. Notice how the Is operator is used when
comparing reference types, and the = operator when comparing value types.

Passing a Value Type by Reference into a Method


Question: In the following code example, what is the value of the myString variable after the
ChangeInput method completes?
Module Module1
Sub Main()
Dim myString As String = "Original value"
ChangeInput(myString)
End Sub
Sub ChangeInput(ByVal input As String)
input = "Changed value"
End Sub
End Module

Answer: The value of the myString variable is Original Value. The issue is that the reference is
passed as the parameter. You can change data through the reference, but if you make the
reference refer somewhere else, it is lost when the method completes, and the original data
is left intact.

Boxing and Unboxing


Question: Is the following code an example of boxing or unboxing?
Dim amount As Object = "1234"
Dim convertedAmount As Integer = CType(amount, Integer)

Answer: Unboxing.

Nullable Types
Question: What is wrong with the following code?
Dim amount As Integer = Nothing
If Not amount Is Nothing Then
...

6-11

6-12

Programming in Visual Basic with Microsoft Visual Studio 2010

End If

Answer: The Integer variable amount has not been declared by using the nullable Integer
type. The following code example illustrates this.
Dim amount? As Integer = Nothing

Programming in Visual Basic with Microsoft Visual Studio 2010

Additional Reading
Passing a Value Type by Reference into a Method
For more information about using the ByRef keyword, see the ByRef (Visual Basic) page.

6-13

6-14

Programming in Visual Basic with Microsoft Visual Studio 2010

Module Reviews and Takeaways


Review questions
Question: When you define the first value in an enumeration, the value defaults to the index
of zero. How can you change the default index?
Answer:
Enum Days As Integer
Monday = 1
Tuesday = 2
Wednesday = 3
End Enum

Question: What is a class?


Answer: A class is a blueprint from which you can create objects. A class defines the
characteristics of an object, such as the data that the object can contain and the operations
that the object can perform.
Question: What keyword can you use to split a class definition over multiple files?
Answer: The Partial keyword.
Question: Is a Boolean variable a value type or a reference type?
Answer: A value type.
Question: How can you pass a value type by reference into a method?
Answer: By using the ByRef keyword.
Question: What is the process called when you explicitly convert a value type to a reference
type?
Answer: Boxing.

Best Practices
Supplement or modify the following best practices for your own work situations.

When you use a series of related constants, create an enumeration to encapsulate those constants
into an object.

Use structures to implement simple concepts whose main feature is their value. Also use structures for
small data items where it is just asor nearly asefficient to copy the value as it would be to copy an
address.

Use classes for more complex data that is too big to copy efficiently.

Programming in Visual Basic with Microsoft Visual Studio 2010

Lab Review Questions and Answers


Question: What type would you use to model a collection of constant values?
Answer: An enumeration type.
Question: At what scope level would you define an enumeration type, if you wanted that
type to be accessible to multiple classes?
Answer: At the namespace scope level.
Question: What construct would you use to model a simple custom numeric type?
Answer: A Structure type.

6-15

Programming in Visual Basic with Microsoft Visual Studio 2010

Module 7
Encapsulating Data and Methods
Contents:
Lesson 1: Controlling Visibility of type Members

Lesson 2: Sharing Methods and Data

Module Reviews and Takeaways

Lab Review Questions and Answers

10

7-1

7-2

Programming in Visual Basic with Microsoft Visual Studio 2010

Lesson 1

Controlling Visibility of Type Members


Contents:
Question and Answers

Additional Reading

Programming in Visual Basic with Microsoft Visual Studio 2010

Question and Answers


What is Encapsulation?
Question: Discuss your experiences of encapsulation with other students.
Answer: This question is designed to stimulate discussion among the students, so there is no
definitive answer.

Comparing Private and Public Members


Question: You have created a class called Product to encapsulate information about the
products that your organization sells. The following code example shows the definition of
this class. You want to use this class in an application that creates Product objects and
displays their details. What is the main problem with the Product class that may mean that a
client application cannot use the Product type in this way?
Public Class Product
' Make these fields private so that an application cannot change
' them after the Product object has been created.
Private productID As Integer
Private productName As String
' Public methods that a client application can use to
' get the product ID and name.
Public Function GetProductID() As Integer
Return Me.productID
End Function
Public Function GetProductName() As tring
Return Me.productName
End Function
' Provide a constructor to enable a client application
' to create a Product object.
Sub New(ByVal ID As Integer, ByVal name As String)
Me.productID = ID
Me.productName = name
End Sub
End Class

Answer: The constructor is private, so you cannot instantiate a Product object to use any of
its public instance members.

Comparing Friend and Public Types


Question: In the Revenue structure that is shown in the preceding code example, the
constructor is defined as Public although the type is defined as Private. Does this mean that
a type other than the Sales type can invoke this constructor?
Answer: The Revenue structure is only accessible to the Sales type.

7-3

7-4

Programming in Visual Basic with Microsoft Visual Studio 2010

Additional Reading
Comparing Private and Public Members
For more information about the access modifiers, see the Private (Visual Basic) page.
For more information about the Public access modifier, see the Public (Visual Basic) page.

Comparing Friends and Public Members


For more information about the Friend access modifier, see the Friends (Visual Basic) page

Programming in Visual Basic with Microsoft Visual Studio 2010

Lesson 2

Sharing Methods and Data


Contents:
Question and Answers

Additional Reading

7-5

7-6

Programming in Visual Basic with Microsoft Visual Studio 2010

Question and Answers


Creating and Using Shared Fields and Static Local Variables
Question: What happens if you try to access a public shared field through an instance of the
type?
Answer: You get a compile error that explains that the member cannot be accessed with an
instance reference.

Creating and Using Shared Methods


Question: The Person class definition in the following code example contains functionality
to calculate the number of years that a person must work before he or she reaches a set
retirement age. The class does not compile; can you identify the problem?
Class Person
Public RetirementAge As Integer
Public Sub New(ByVal retirementAge As Integer)
Me.RetirementAge = retirementAge
End Sub
Shared Public Function CalculateRemainingWorkYears(ByVal age As Integer) As
Integer
Return Me.RetirementAge - age
End Function
End Class

Answer: The CalculateRemainingWorkYears method is Shared, but the RetirementAge


field is an instance.

Creating and Using Shared Constructors


Question: Identify the errors in the class definition in the following code example.
Class Person
Private ageLimit As Integer
Shared Private Sub New(ByVal ageLimit As Integer)
Me.ageLimit = ageLimit
End Sub
Shared Public Function GetAllNames() As String()
Throw New NotImplementedException()
End Function
End Class

Answer: The class has the following errors:

You cannot explicitly set an access modifier on a shared constructor.

The constructor must be parameter less.

A shared constructor cannot access an instance field.

Creating and Using Extension Methods


Question: Briefly explain the difference between a standard methods signature and a
signature for an extension method.

Programming in Visual Basic with Microsoft Visual Studio 2010

Answer: An extension method must be declared in a Module; the first parameter represents
the type that you want to extend, and the method must be decorated with the Extension
attribute.

7-7

7-8

Programming in Visual Basic with Microsoft Visual Studio 2010

Additional Reading
Creating and Using Shared Methods
For more information about the static modifier, see the Shared (Visual basic) page.

Creating and Using Extension Methods


For more information about extension methods, see the Extension Methods (Visual Basic) page.

Programming in Visual Basic with Microsoft Visual Studio 2010

7-9

Module Reviews and Takeaways


Review questions
Question: Briefly explain the purpose of encapsulation.
Answer: The purpose of encapsulation is to hide the internal data and implementation
details of a type, so that only specific parts of the type are accessible to applications.
Question: Which access modifier do you use to expose a method to a type in a different
assembly?
Answer: The Public access modifier.
Question: How do you invoke a shared constructor?
Answer: You do not explicitly invoke shared constructors. The common language runtime
(CLR) invokes them before you use the shared type.

Best Practices Related to Encapsulating Data and Methods


Supplement or modify the following best practices for your own work situations:

Do not expose the inner workings of your types with the Public and Friend access modifiers. If in
doubt, use the Private access modifier.

If a type does not need to store instance data, declare the type as static.

If you must add functionality to an existing type and do not want to derive a new type, use extension
methods.

7-10

Programming in Visual Basic with Microsoft Visual Studio 2010

Lab Review Questions and Answers


Question: Which access modifier would you use to stop fields being accessed from outside
the parent type?
Answer: The Private access modifier.
Question: When declaring a constructor in a shared type, how many parameters can the
constructor take?
Answer: The constructor must be parameter less.
Question: When declaring an extension method, which attribute must you use to decorate
the first method?
Answer: The ExtensionAttribute attribute.

Programming in Visual Basic with Microsoft Visual Studio 2010

Module 8
Inheriting from Classes and Implementing Interfaces
Contents:
Lesson 1: Using Inheritance to Define New Reference Types

Lesson 2: Defining and Implementing Interfaces

Lesson 3: Defining Abstract Classes

11

Module Reviews and Takeaways

17

Lab Review Questions and Answers

18

8-1

8-2

Programming in Visual Basic with Microsoft Visual Studio 2010

Lesson 1

Using Inheritance to Define New Reference Types


Contents:
Question and Answers

Additional Reading

Detailed Demo Steps

Programming in Visual Basic with Microsoft Visual Studio 2010

Question and Answers


What is Inheritance?
Question: Which accessor should you use to make class members accessible to child classes?
Answer: The Protected accessor. The Protected accessor permits access to the current class
and classes that inherit from it only.

.NET Framework Inheritance Hierarchy


Question: What types inherit from the Object class?
Answer: All types inherit from the Object class, including reference and value types.

Overriding and Hiding Methods


Question: What happens if you attempt to hide a method without using the Shadows
keyword?
Answer: The compiler will assume that you meant to hide the existing method and your
code will compile; however, the compiler will generate a warning suggesting that you use
the Shadows keyword.

Calling Methods and Constructors in a Base Class


Question: What happens if you do not call the constructor of a base class in the constructor
for your class?
Answer: The compiler automatically calls the default constructor of the base class. If the base
class does not have a public default constructor, the code will not compile.

Assigning and Referencing Classes in an Inheritance Hierarchy


Question: What exception is thrown if you attempt to perform an invalid conversion or cast?
Answer: An InvalidCastException exception is thrown at runtime if you attempt to perform
an invalid conversion.

Understanding Polymorphism
Question: When you reference an object by its parent class, which version of a method is
called: the version from the base class or the overridden version in the child class?
Answer: When a method is overridden in the child class, the version in the child class will
always be used. Referencing an object by using the parent class will not change this behavior.

Defining Sealed Classes and Methods


Question: Can you define a class that inherits from the Visual Basic Integer type?
Answer: No. The Integer type is a value type; it is implicitly sealed.

Demonstration: Using Inheritance to Construct New Reference Types


Question: Which functionality does Visual Studio provide when you implement an interface?
Answer: The Visual Studio the Code Editor implements the class members, if you place the
cursor at the end of the Implements interfacename line of code, and then press Enter.

8-3

8-4

Programming in Visual Basic with Microsoft Visual Studio 2010

Additional Reading
.NET Framework Inheritance Hierarchy
For more information about the Object class, see the Object Class page.

Assigning and Referencing Classes in an Inheritance Hierarchy


For more information about the TryCast keyword, see the TryCast Operator (Visual Basic) page.
For more information about the TypeOf...Is operator, see the TypeOf Operator (Visual Basic) page.

Understanding Polymorphism
For more information about polymorphism, see the Polymorphism page.

Programming in Visual Basic with Microsoft Visual Studio 2010

8-5

Detailed Demonstration Steps


Demonstration: Using Inheritance to Construct New Reference Types
Detailed demonstration steps
1.

Open Microsoft Visual Studio 2010:


a.

2.

3.

Click Start, point to All Programs, click Microsoft Visual Studio 2010, and then click
Microsoft Visual Studio 2010.

Open the Module 8, Demo1 starter solution:


a.

In Visual Studio, on the File menu, click Open Project.

b.

Browse to the D:\Demofiles\Mod8\Demo1\Starter folder, and then double-click


UsingInheritanceDemo.sln.

Add a Television class to the Module1.vb file:


a.

In Solution Explorer, double-click Module1.vb. Add the following code to the file:

Class Television
End Class

4.

Add a Protected Overridable method named SetCurrentChannel to the Television class.


The method should write a message to the console indicating that the channel has been set.
Your code should resemble the following code example.
Class Television
Protected Overridable Sub SetCurrentChannel()
Console.WriteLine("Channel set.")
End Sub
End Class

5.

In the Television class, add a Protected method called TurnOn. The method should write a
message to the console indicating that the television is on. Your code should resemble the
following code example.
Class Television
Protected Overridable Sub SetCurrentChannel()
Console.WriteLine("Channel set.")
End Sub
Protected Sub TurnOn()
Console.WriteLine("Television on.")
End Sub
End Class

6.

In the Module1.vb file, add a new class called WidescreenTV that inherits from the
Television class. Your code should resemble the following code example.
Class WidescreenTV
Inherits Television
End Class

8-6

Programming in Visual Basic with Microsoft Visual Studio 2010

7.

Override the SetCurrentChannel method. The method should write a message to the screen
indicating that the channel has been set on the widescreen television. Your code should
resemble the following code example.
Class WidescreenTV
Inherits Television
Protected Overrides Sub SetCurrentChannel()
Console.WriteLine("Widescreen channel set.")
End Sub
End Class

8.

Add a constructor to the WidescreenTV class. The constructor should call the constructor of
the base class, call the TurnOn method, call the SetCurrentChannel method, and then call
the SetCurrentChannel method of the base class. Your code should resemble the following
code example.
Class WidescreenTV
Inherits Television
Protected Overrides Sub SetCurrentChannel()
Console.WriteLine("Widescreen channel set.")
End Sub
Public Sub New()
MyBase.New()
TurnOn()
SetCurrentChannel()
MyBase.SetCurrentChannel()
End Sub
End Class

9.

Uncomment the code in the Program class that creates an instance of the WidescreenTV
class.

10. Run the application with debugging and verify that the following messages appear.
Television on.
Widescreen channel set.
Channel set.

Programming in Visual Basic with Microsoft Visual Studio 2010

Lesson 2

Defining and Implementing Interfaces


Contents:
Question and Answers

Detailed Demonstration Steps

8-7

8-8

Programming in Visual Basic with Microsoft Visual Studio 2010

Question and Answers


What is an Interface?
Question: Can you add a default implementation of a method to an interface?
Answer: No. An interface only contains definitions for methods and other class members; it
does not contain any implementation. Default implementations can be added to abstract
classes, which are covered later in this module.

Creating and Implementing an Interface


Question: When you define an interface, do you add a method body?
Answer: No. An interface only contains a method definition.

Referencing an Object Through an Interface


Question: What happens if you attempt to convert or cast an object to an interface that it
does not implement?
Answer: Just like object conversion or casting, this will cause an InvalidCastException
exception.

Demonstration: Creating an Interface


Question: What is the recommended naming convention when defining interfaces?
Answer: Interface names should be prefixed with an uppercase I.

Programming in Visual Basic with Microsoft Visual Studio 2010

8-9

Detailed Demonstration Steps


Demonstration: Creating an Interface
Detailed demonstration steps
1.

Open Microsoft Visual Studio 2010.

2.

In Visual Studio 2010, open the CreatingAnInterfaceDemo solution in the


D:\Demofiles\Mod8\Demo2\Starter folder.

3.

In the Module1.vb file, add an interface called ITelevision. Your code should resemble the
following code example.
Interface ITelevision
End Interface

4.

Add a TurnOn method to the interface. Your code should resemble the following code
example.
Interface ITelevision
Sub TurnOn()
End Interface

5.

Add a TurnOff method to the interface. Your code should resemble the following code
example.
Interface ITelevision
Sub TurnOn()
Sub TurnOff()
End Interface

6.

Add an IncreaseVolume method to the interface. Your code should resemble the following
code example.
Interface ITelevision
Sub TurnOn()
Sub TurnOff()
Sub IncreaseVolume()
End Interface

7.

Add a DecreaseVolume method to the interface. Your code should resemble the following
code example.
Interface ITelevision
Sub TurnOn()
Sub TurnOff()
Sub IncreaseVolume()
Sub DecreaseVolume()
End Interface

8.

In the Module1.vb file, add a class called Television that implements the ITelevision
interface. Your code should resemble the following code example.
Class Television
Implements ITelevision
End Class

8-10

Programming in Visual Basic with Microsoft Visual Studio 2010

9.

In the definition of the Television class, implement the ITelevision interface by using the
tools in Visual Studio.
a.

Place the cursor at the end of the Implement Interface line of code, and then press
Enter.

Programming in Visual Basic with Microsoft Visual Studio 2010

Lesson 3

Defining Abstract Classes


Contents:
Question and Answers

12

Additional Reading

13

Detailed Demonstration Steps

14

8-11

8-12

Programming in Visual Basic with Microsoft Visual Studio 2010

Question and Answers


What is an Abstract Class?
Question: Can a method in an abstract class contain a default implementation?
Answer: Yes. This is the big advantage of using an abstract class: common functionality can
be abstracted into an abstract class so that code does not need to be duplicated. If a method
in an abstract class is marked Overrides or Overridable, you can override the default
functionality in a child class.

What is an Abstract Method?


Question: Can an abstract method contain a default implementation?
Answer: No. However, a concrete method in an abstract class can contain a default
implementation.

Demonstration: Creating an Abstract Class


Question: Can you combine abstract and nonabstract (concrete) methods in an abstract
class?
Answer: Yes. You can use any combination of abstract and concrete methods in an abstract
class.

Programming in Visual Basic with Microsoft Visual Studio 2010

Additional Reading
What is an Abstract Class?
For more information about the MustInherit modifier, see the MustInherit (Visual Basic) page.

What is an Abstract Method?


For more information about MustOverride members, see the MustOverride (Visual Basic) page.

8-13

8-14

Programming in Visual Basic with Microsoft Visual Studio 2010

Detailed Demonstration Steps


Demonstration: Creating an Abstract Class
Detailed demonstration steps
1.

Open Microsoft Visual Studio 2010.

2.

In Visual Studio 2010, open the CreatingAnAbstractClassDemo solution in the


D:\Demofiles\Mod8\Demo3\Starterfolder.

3.

In the Module1.vb file, add an abstract class called Television. Your code should resemble
the following code example.
MustInherit Class Television
End Class

4.

Add a public TurnOn method to the class. The method should write a message to the
console indicating that the television is on. Your code should resemble the following code
example.
MustInherit Class Television
Public Sub TurnOn()
Console.WriteLine("Television on.")
End Sub
End Class

5.

Add a public TurnOff method to the class. The method should write a message to the
console indicating that the television is off. Your code should resemble the following code
example.
MustInherit Class Television
Public Sub TurnOn()
Console.WriteLine("Television on.")
End Sub
Public Sub TurnOff()
Console.WriteLine("Television off.")
End Sub
End Class

6.

Add a public abstract IncreaseVolume method to the class. Your code should resemble the
following code example.
MustInherit Class Television
Public Sub TurnOn()
Console.WriteLine("Television on.")
End Sub
Public Sub TurnOff()
Console.WriteLine("Television off.")
End Sub
Public MustOverride Sub IncreaseVolume()
End Class

Programming in Visual Basic with Microsoft Visual Studio 2010

7.

8-15

Add a public abstract DecreaseVolume method to the class. Your code should resemble the
following code example.
MustInherit Class Television
Public Sub TurnOn()
Console.WriteLine("Television on.")
End Sub
Public Sub TurnOff()
Console.WriteLine("Television off.")
End Sub
Public MustOverride Sub IncreaseVolume()
Public MustOverride Sub DecreaseVolume()
End Class

8.

In the Module1.vb file, add a class called WidescreenTV that inherits from the abstract
Television class. Your code should resemble the following code example.
Class WidescreenTV
Inherits Television
End Class

9.

Override the IncreaseVolume method. The method should write a message to the screen
indicating that the volume has increased on the widescreen television. Your code should
resemble the following code example.
Class WidescreenTV
Inherits Television
Public Overrides Sub IncreaseVolume()
Console.WriteLine("Volume increased (WidescreenTV).")
End Sub
End Class

10. Override the DecreaseVolume method. The method should write a message to the screen
indicating that the volume has decreased on the widescreen television. Your code should
resemble the following code example.
Class WidescreenTV
Inherits Television
Public Overrides Sub IncreaseVolume()
Console.WriteLine("Volume increased (WidescreenTV).")
End Sub
Public Overrides Sub DecreaseVolume()
Console.WriteLine("Volume decreased (WidescreenTV).")
End Sub
End Class

11. In the Module1.vb file, add a class called TV that inherits from the abstract Television class.
Your code should resemble the following code example.
Class TV
Inherits Television
End Class

8-16

Programming in Visual Basic with Microsoft Visual Studio 2010

12. Override the IncreaseVolume method. The method should write a message to the screen
indicating that the volume has increased on the television. Your code should resemble the
following code example.
Class TV
Inherits Television
Public Overrides Sub IncreaseVolume()
Console.WriteLine("Volume increased (TV).")
End Sub
End Class

13. Override the DecreaseVolume method. The method should write a message to the screen
indicating that the volume has increased on the television. Your code should resemble the
following code example.
Class TV
Inherits Television
Public Overrides Sub IncreaseVolume()
Console.WriteLine("Volume increased (TV).")
End Sub
Public Overrides Sub DecreaseVolume()
Console.WriteLine("Volume decreased (TV).")
End Sub
End Class

14. Uncomment the code in the Module1module.


15. Run the application with debugging.

Programming in Visual Basic with Microsoft Visual Studio 2010

8-17

Module Reviews and Takeaways


Review questions
Question: What is the role of the Object class in the .NET Framework?
Answer: The Object class is the ultimate base class of all types, including reference and value
types.
Question: What are the advantages of using an abstract class over an interface?
Answer: An abstract class can contain default implementations of methods, whereas an
interface can never contain any implementation.

Best Practices Related to Inheritance


Supplement or modify the following best practices for your own work situations:

Create an inheritance hierarchy where appropriate to reduce code duplication.

Where appropriate, mark methods as Overridable to enable child classes to override them.

Where appropriate, mark methods as NotOverridable to prevent child classes from overriding them.

Where appropriate, mark classes as NotInheritable to prevent classes from inheriting from them.

Best Practices Related to Interfaces


Supplement or modify the following best practices for your own work situations:

Use interfaces wherever possible as a contract that specifies what methods a class will expose.

Prefix an interface with an upper case I.

Best Practices Related to Abstract Classes


Supplement or modify the following best practices for your own work situations:

Use abstract classes to abstract common functionality and reduce code duplication.

Use abstract methods to guarantee that an inheriting class overrides a method.

8-18

Programming in Visual Basic with Microsoft Visual Studio 2010

Lab Review Questions and Answers


Question: What steps are required to implement an interface?
Answer: The class must inherit from the interface and provide an implementation of all
methods that the interface defines.
Question: How do you implement an abstract class?
Answer: You use the MustInherit modifier and develop the class in the same manner as
other classes. You can add abstract (MustOverride) methods that have no implementation,
but must be implemented instead by any classes that inherit from the abstract class.

Programming in Visual Basic with Microsoft Visual Studio 2010

9-1

Module 9
Managing the Lifetime of Objects and Controlling Resources
Contents:
Lesson 1: Introduction to Garbage Collection

Lesson 2: Managing Reosurces

Module Reviews and Takeaways

11

Lab Review Questions and Answers

12

9-2

Programming in Visual Basic with Microsoft Visual Studio 2010

Lesson 1

Introduction to Garbage Collection


Contents:
Question and Answers

Additional Reading

Detailed Demo Steps

Programming in Visual Basic with Microsoft Visual Studio 2010

Question and Answers


Object Life Cycle
Question: How can you control the creation phase for an object?
Answer: You add a constructor to the class.

Managed Resources in the .NET Framework


Question: Is the stack a first in, first out (FIFO), last in, first out (LIFO), first in, last out (FILO),
or random access memory store?
Answer: The stack is a LIFO structure.

How Does the Garbage Collector Work?


Question: What is the purpose of the freachable queue?
Answer: The freachable queue contains pointers to objects that are waiting for finalization.

Defining a Destructor/Finalizer
Question: Can you add a destructor to a structure?
Answer: No. You can only add a destructor to a class.

GC Class
Question: How can you inform the runtime that you need to allocate a large block of
unmanaged memory?
Answer: You can use the AddMemoryPressure method of the GC class.

Demonstration: Implementing a Destructor/Finalizer


Question: How can you delay execution of the current thread until all objects in the
finalization queue are finalized?
Answer: You can use the WaitForPendingFinalizers method of the GC class.

9-3

9-4

Programming in Visual Basic with Microsoft Visual Studio 2010

Additional Reading
Managed Resources in the .NET Framework
For more information about memory management, see the Object Lifetime: How Objects Are Created and
Destroyed (Visual Basic) page.

GC Class
For more information about the GC class, see the GC Class page.

Programming in Visual Basic with Microsoft Visual Studio 2010

9-5

Detailed Demonstration Steps


Demonstration: Implementing a Destructor/Finalizer
Detailed demonstration steps
1.

Start Microsoft Visual Studio 2010:


a.

2.

3.

Click Start, point to All Programs, click Microsoft Visual Studio 2010, and then
click Microsoft Visual Studio 2010.

Open the Module 9, Demo1 starter solution:


a.

On the File menu, click Open Project.

b.

Browse to the D:\Demofiles\Mod9\Demo1\Starter folder, and then double-click


Destructor Demo.sln.

In the Employee.vb file, implement the IDisposable interface, and generate the method
stubs. Uncomment the Finalize method, and add code to write the current salary to the
SalaryDetails.txt file, when the object is finalized:
a.

In Solution Explorer, double-click Employee.vb.

b.

Add the code in bold in the following code example to the file.

Dispose(False)
File.WriteAllText("SalaryDetails.txt", salary.ToString())
Console.WriteLine("Employee finalized: {0}", name)

4.

Walk the students through the other code in the Employee class. Highlight the code that
reads the current salary from a text file.

5.

Show the students the code in the Module1.vb file. Highlight that each employee is given a
pay rise and then the object reference is removed. Explain that this will make the object
available for garbage collection and that the destructor will write the updated salary back to
the file.

6.

Run the application.


a.

On the Debug menu, click Start Debugging.

7.

Point out that all the employees are paid the same amount; the pay increases do not reflect
the update made to the text file by the destructor. Remind students that the garbage
collector only runs when it needs to, and this program does not create enough objects or use
enough memory to cause a collection.

8.

Stop the application.


a.

9.

On the Debug menu, click Stop Debugging.

In the Module1.vb file, uncomment the call to the AddMemoryPressure method. Explain
that this makes the garbage collector free as much memory as possible, ready for a large
allocation of unmanaged memory.

10. Run the application.

9-6

Programming in Visual Basic with Microsoft Visual Studio 2010

Lesson 2

Managing Resources
Contents:
Question and Answers

Additional Reading

Detailed Demonstration Steps

Programming in Visual Basic with Microsoft Visual Studio 2010

Question and Answers


Why Manage Resources in a Managed Environment?
Question: What types of resources may need to be managed correctly?
Answer: Resources that are valuable, such as database connections, file operations, or
objects that cache data in memory.

What Is the Dispose Finalize Pattern?


Question: What exception should you throw in your class if you attempt to use it after it has
been disposed?
Answer: You should throw an ObjectDisposedException exception.

Managing Resources in Your Applications


Question: If you do not dispose of an object when you have finished with it, will the runtime
call the Dispose method automatically?
Answer: No. The runtime will not call the Dispose method; you must always add the code to
call the Dispose method yourself.

Demonstration: Using the Dispose Finalize Pattern


Question: What is the preferred construct for managing resources in an application?
Answer: Implement the dispose pattern and use a Using statement to manage resources.

9-7

9-8

Programming in Visual Basic with Microsoft Visual Studio 2010

Additional Reading
What Is the Dispose Finalize Pattern?
For more information about the Dispose Finalize pattern, see the How to: Implement the Dispose
Finalize Pattern (Visual Basic) page.

Demonstration: Using the Dispose Finalize Pattern


For more information about the Using statement, see the Using Statement (Visual Basic) page.

Programming in Visual Basic with Microsoft Visual Studio 2010

9-9

Detailed Demonstration Steps


Demonstration: Using the Dispose Finalize Pattern
Detailed demonstration steps
1.

Start Visual Studio 2010:


a.

2.

3.

Click Start, point to All Programs, click Microsoft Visual Studio 2010, and then
click Microsoft Visual Studio 2010.

Open the Module 9, Demo2 starter solution:


a.

On the File menu, click Open Project.

b.

Browse to the D:\Demofiles\Mod9\Demo2\Starter folder, and then double-click


DisposeFinalize Demo.sln.

Modify the Employee class to implement the IDisposable interface. The code should follow
best practices. Explain to students that although the call to GC.SuppressFinalize in the
Dispose method is unnecessary at present, it is still worth including it, in case a finalizer is
added to the Employee class later. Your code should resemble the following code example.
Public Class Employee
Implements IDisposable
Private name As String
Public Sub New(ByVal name As String)
Me.name = name
End Sub
Public Sub PaySalary()
If Not Me.disposedValue Then
Console.WriteLine("Employee {0} paid.", Me.name)
Else
Throw New ObjectDisposedException( _
"Employee already disposed.")
End If
End Sub
#Region "IDisposable Support"
Private disposedValue As Boolean ' To detect redundant calls
' IDisposable
Protected Overridable Sub Dispose(ByVal disposing As Boolean)
If Not Me.disposedValue Then
If disposing Then
' TODO: dispose managed state (managed objects).
End If
' TODO: free unmanaged resources (unmanaged objects) and
'
override Finalize() below.
' TODO: set large fields to null.
End If
Me.disposedValue = True
End Sub
' TODO: override Finalize() only if Dispose(ByVal disposing As
'
Boolean) above has code to free unmanaged resources.

9-10

Programming in Visual Basic with Microsoft Visual Studio 2010

'Protected Overrides Sub Finalize()


' ' Do not change this code.
' ' Put cleanup code in Dispose(ByVal disposing As Boolean)
' 'above.
' Dispose(False)
' MyBase.Finalize()
'End Sub
' This code added by Visual Basic to correctly implement the
' disposable pattern.
Public Sub Dispose() Implements IDisposable.Dispose
' Do not change this code.
' Put cleanup code in Dispose(ByVal disposing As Boolean)
' above.
Dispose(True)
GC.SuppressFinalize(Me)
End Sub
#End Region
End Class

4.

Uncomment the Finalize method.

5.

Walk students through the Module1 module. Show them the Using construct and the inline
code. Explain that the Using statement is exception safe and the inline code is not exception
safe.

6.

Run the application:


a.

Press Ctrl+F5.

7.

When the application pauses, press Enter.

8.

Point out the unhandled exception. Explain that the Using statement prevented these
exceptions.

Programming in Visual Basic with Microsoft Visual Studio 2010

9-11

Module Reviews and Takeaways


Review questions
Question: What methods are defined in the IDisposable interface?
Answer: The IDisposable interface includes a Dispose method that takes no parameters
and returns nothing.
Question: Where would an instance of the System.String class be stored: on the heap or on
the stack?
Answer: The String class is a class. Therefore, it is a reference type that is stored on the heap.
Question: Should you implement the Dispose pattern for every class you develop?
Answer: No. You should only implement the Dispose pattern where necessary. Implementing
the Dispose pattern to a class significantly lengthens the time for the memory used by an
object to be reclaimed (even if the Dispose method does nothing).

Best Practices Related to Disposing of Unmanaged Objects


Help the students understand the best practices presented in this section. Ask students to consider these
best practices in the context of their own business situations:

You should implement the Dispose pattern whenever your code uses unmanaged resources.

You should use a Using statement to ensure disposal of objects wherever possible.

Where a Using statement is not appropriate, you should ensure exception-safe disposal of objects by
using a Try/Finally block; you should release resources in the Finally block.

9-12

Programming in Visual Basic with Microsoft Visual Studio 2010

Lab Review Questions and Answers


Question: Why do you implement the Dispose Finalize pattern?
Answer: You implement the Dispose Finalize pattern to ensure that resources are released,
managed and unmanaged, when the object is no longer needed.
Question: What is the syntax of the Using statement?
Answer: You use the Using keyword, followed by a variable declaration. You then append to
the block of code that uses the defined variable, an End Using statement.

Programming in Visual Basic with Microsoft Visual Studio 2010

Module 10
Encapsulating Data and Defining Overloaded Operators
Contents:
Lesson 1: Creating and Using Properties

Lesson 2: Creating and Using Indexers

Lesson 3: Overloading Operators

12

Module Reviews and Takeaways

17

Lab Review Questions and Answers

18

10-1

10-2

Programming in Visual Basic with Microsoft Visual Studio 2010

Lesson 1

Creating and Using Properties


Contents:
Question and Answers

Additional Reading

Detailed Demo Steps

Programming in Visual Basic with Microsoft Visual Studio 2010

Question and Answers


What Is a Property?
Question: How does the performance of a method differ from a property?
Answer: A method can take a set of parameters of various types, and it performs a function.
A property is assigned a single value and is intended to set a value, not perform a function. A
property may perform some functionality as a side effect of the assignment, but this should
not be the purpose of the property.

Defining a Property
Question: How can you enable write access to a property to other types in the same
assembly, but read access to a property from a class in any assembly?
Answer: Declare a public property, but mark the Set procedure Friend.

Auto-Implemented Properties
Question: What is the benefit of using an auto-implemented property, compared to
exposing a public field?
Answer: An auto-implemented property is simply another property to consuming
applications. If you must change your type in the future, and you must change a field to a
property, any consuming application must be recompiled; however, if you simply change
from an auto-implemented property to a manually implemented property, the change is
invisible to the consuming application.

Instantiating an Object by Using Object Initializers


Question: Why is it important to instantiate required properties to default values in the
constructor?
Answer: Object initializers do not require consuming code to set a specific set of fields. A
consuming class may fail to set all of the required fields in the object initializer. This may
cause errors when the object is used. Setting all required properties to default values in the
constructor should avoid this problem.

Defining Properties in an Interface


Question: When should you add a property to an interface?
Answer: You should add a property to an interface when it exposes data that is important
for consuming classes to access and where the exposure of that property is crucial to the
intended purpose of the interface.

Best Practices When Defining and Using Properties


Question: When should you add a property to an interface?
Answer: If you are writing code for a secure environment where you must log access to the
data.

10-3

10-4

Programming in Visual Basic with Microsoft Visual Studio 2010

Demonstration: Using Properties


Question: If you set a property in a constructor, and you use named properties to set the
same property when you instantiate the object, which takes precedence: the value from the
constructor or the named property?
Answer: The named property. The constructor runs first, and then the named properties are
applied; therefore, they overwrite any properties set in the constructor.

Programming in Visual Basic with Microsoft Visual Studio 2010

Additional Reading
What Is a Property?
For more information about properties, see the Property Procedures (Visual Basic) page.

10-5

10-6

Programming in Visual Basic with Microsoft Visual Studio 2010

Detailed Demonstration Steps


Demonstration: Using Properties
Detailed demonstration steps
1.

Start Microsoft Visual Studio 2010:


a.

2.

3.

Open the Module 10, Demo1 starter solution:


a.

On the File menu, click Open Project.

b.

Browse to the D:\Demofiles\Mod10\Demo1\Starter folder, and then double-click


UsingPropertiesDemo.sln.

Open the Employee.vb file, and then review the Employee class. Highlight the publicly
exposed fields. Also highlight the constructor that sets the Name field based on the
parameter and the Salary and Department fields to default values:
a.

4.

Click Start, point to All Programs, click Microsoft Visual Studio 2010, and then
click Microsoft Visual Studio 2010.

In Solution Explorer, double-click Employee.vb, and then explain the contents of


the class.

Convert the Name field to a property by using auto-implemented properties:


Modify the following line of code.
Public Name As String
Change it to the following line of code.
Public Property Name As String

5.

Convert the Department field to a property by using auto-implemented properties:


Modify the following line of code.
Public Department As String
Change it to the following line of code.
Public Property Department As String

6.

Convert the Public Salary field to a Private field and rename it empSalary:
Modify the following line of code.
Public Salary As Integer
Change it to the following line of code.
Private empSalary As Integer

7.

Uncomment the commented Salary property, and then explain how it ensures that an
employee can never have a negative salary.

8.

Open the Module1.vb file, and then review the Employee object
a.

9.

In Solution Explorer, double-click Module1.vb, and then explain the contents of the
object.

Uncomment all the code up to and including the first occurrence of the following code.

Programming in Visual Basic with Microsoft Visual Studio 2010

10-7

Console.ReadLine()

10. Describe the code that you have just uncommented:


a.

Explain how the julie object is created by using the constructor, and explain that the
properties are subsequently set by using the dot notation.

b.

Explain how the james object is created by using named properties. Emphasize that
these named properties are set after the constructor is run, so they take precedence
over the default values set by the constructor.

11. Uncomment the remaining code in the file.


12. Describe the code that you have just uncommented:
a.

Explain that the code attempts to set James salary to a negative value. Remind
students that the property prevented negative values.

13. Run the application:


a.

Press Ctrl+F5.

14. When the application pauses, highlight that the application has worked as expected, and the
two employees details are displayed correctly, and then press Enter.
15. When the application pauses, highlight that the application has worked as expected, and
James salary has been set to 0 instead of a negative value, and then press Enter.
16. Close Visual Studio:
a.

In Visual Studio, on the File menu, click Exit.

10-8

Programming in Visual Basic with Microsoft Visual Studio 2010

Lesson 2

Creating and Using Default Properties


Contents:
Question and Answers

Additional Reading

10

Detailed Demonstration Steps

11

Programming in Visual Basic with Microsoft Visual Studio 2010

Question and Answers


What Is a Default Property?
Question: When may you want to add a default property to a type?
Answer: When the type exposes a set of data to which you want to enable access to
individual members.

Creating a Default Property


Question: What information should you use as parameters for a default property?
Answer: You should only use parameters that are necessary to locate an individual data
member in the dataset. You should not use parameters to manipulate data.

Demonstration: Creating and Using a Default Property


Question: Can you develop more than one default property with the same set of
parameters?
Answer: No. You cannot define several default properties with the same set of parameters.
However, as with other procedures, you can overload a default property by using different
parameters.

10-9

10-10

Programming in Visual Basic with Microsoft Visual Studio 2010

Additional Reading
Creating a Default Property
For more information about using default properties, see the How to: Declare and Call a Default
Property in Visual Basic page.

Programming in Visual Basic with Microsoft Visual Studio 2010

10-11

Detailed Demonstration Steps


Demonstration: Creating and Using a Default Property
Detailed demonstration steps
1.

Start Visual Studio:


a.

2.

3.

Click Start, point to All Programs, click Microsoft Visual Studio 2010, and then
click Microsoft Visual Studio 2010.

Open the Module 10, Demo2 starter solution:


a.

On the File menu, click Open Project.

b.

Browse to the D:\Demofiles\Mod10\Demo2\Starter folder, and then double-click


CreatingAndUsingAnIndexerDemo.sln.

Open the EmployeeDatabase.vb file, and then review the EmployeeDatabase class:
a.

In Solution Explorer, double-click EmployeeDatabase.vb, and then describe the


class.

b.

Highlight that the class stores an array of Employee objects.

c.

Highlight the AddToDatabase method, and then explain how it adds Employee
objects to the array and increments a pointer to the top of the array.

4.

Uncomment the default property that returns an Employee object. Explain how the default
property takes a String parameter called name and iterates through each employee in the
array until it finds one with a matching Name property. It then returns that value. If it does
not find a match after iterating over the entire array, it throws an
IndexOutOfRangeException.

5.

Open the Module1.vb file, and then describe the module:

6.

In the Module1.vb file, uncomment the commented code, and then explain how this code
uses the default property to retrieve Employee instances by specifying the employee name.
Remind students that this would not be possible with an array because you can only access
an array by index.
a.

7.

In Solution Explorer, double-click Module1.vb, and then explain how the class
creates an instance of the EmployeeDatabase class and then adds several
Employee objects to the class.

Run the application:


a.

Press Ctrl+F5.

8.

Highlight that the application runs as expected, and the details of the two employees
retrieved from the database are displayed correctly, and then press Enter.

9.

Close Visual Studio:


a.

In Visual Studio, on the File menu, click Exit.

10-12

Programming in Visual Basic with Microsoft Visual Studio 2010

Lesson 3

Overloading Operators
Contents:
Question and Answers

13

Additional Reading

14

Detailed Demonstration Steps

15

Programming in Visual Basic with Microsoft Visual Studio 2010

Question and Answers


What Is Operator Overloading?
Question: If you overload the + operator in a type, does the compiler automatically
generate an equivalent operator?
Answer: No. The compiler does not generate any operators for you.

Overloading an Operator
Question: Does the first operand of an overloaded operator have to be the containing type?
Answer: No. At least one of the operands has to be the containing type, but there is no
requirement for it to be the first operand.

Restrictions When Overloading Operators


Question: How can you change the multiplicity of an operator?
Answer: You cannot change the multiplicity of an operator; instead, you should define a
method to perform the operation.

Best Practices When Overloading Operators


Question: Why should you always return a new object rather than update one of the
operands?
Answer: There may be several references to the operand. Updating the operand may have
an unexpected effect on other instances.

Implementing and Using Conversion Operators


Question: When should you use an narrowing or explicit conversion?
Answer: You should use a narrowing conversion when the conversion may lead to loss of
data or where there is a risk of an exception.

Demonstration: Overloading an Operator


Question: When can you use the += syntax to abbreviate an addition operation?
Answer: You can use the += syntax when the first operand and the return type of the
addition operation are the same type.

10-13

10-14

Programming in Visual Basic with Microsoft Visual Studio 2010

Additional Reading
Restrictions When Overloading Operators
For more information about using the Equals method, see the Object.Equals Method (Object) page.

Programming in Visual Basic with Microsoft Visual Studio 2010

10-15

Detailed Demonstration Steps


Demonstration: Overloading an Operator
Detailed demonstration steps
1.

Start Visual Studio:


a.

2.

3.

Click Start, point to All Programs, click Microsoft Visual Studio 2010, and then
click Microsoft Visual Studio 2010.

Open the Module 10, Demo3 starter solution:


a.

On the File menu, click Open Project.

b.

Browse to the D:\Demofiles\Mod10\Demo3\Starter folder, and then double-click


OverloadingAnOperator.sln.

Open the EmployeeDatabase.vb file, and then review the EmployeeDatabase class:
a.

In Solution Explorer, double-click EmployeeDatabase.vb, and then describe the


class.

b.

Highlight that the class stores an array of Employee objects and is the same as in
the previous demonstration.

4.

Uncomment the + operator that returns an EmployeeDatabase object. Explain how the +
operator takes an EmployeeDatabase object and an Employee object as parameters, adds
the Employee object to the database, and then returns a reference to the database.

5.

Open the Module1.vb file, and then describe the class:

6.

In the Module1.vb file, uncomment the commented code, and then explain how this code
adds several Employee objects to the database by using both the + syntax and the +=
syntax.
a.

7.

In Solution Explorer, double-click Module1.vb, and then explain how the class
creates an instance of the EmployeeDatabase class and then adds several
Employee objects to the class.

Run the application:


a.

Press Ctrl+F5.

8.

Highlight that the application runs as expected, and the details of the two employees
retrieved from the database are displayed correctly, and then press Enter.

9.

Close Visual Studio:


a.

In Visual Studio, on the File menu, click Exit.

10-16

Programming in Visual Basic with Microsoft Visual Studio 2010

Module Reviews and Takeaways


Review questions
Question: If you are developing a new type and must expose data, how can you expose the
data as a property with minimal extra effort?
Answer: You can use an auto-implemented property. An auto-implemented property is
quick to use and helps to ensure forward compatibility, if your logic must change in the
future.
Question: You must develop an application to represent a set of data. You must expose
individual members of the data to consuming classes. How can you expose individual
members in a dataset to consuming classes?
Answer: You can use a default property to expose individual items in the dataset.
Question: You have overloaded the = operator in a type you are developing. As required by
the compiler, and to comply with best practices, you are also going to implement the <>
operator. Should you implement the <> operator from scratch, or should you use the =
operator that you have already defined, and negate the result?
Answer: You should implement the operator from scratch. Checking whether an object is
not equal can often be performed more efficiently than negating the result of checking
whether an object is equal, and you should aim to write the most efficient code you can.

Best Practices Related to Properties


Help the students understand the best practices presented in this section. Ask students to consider these
best practices in the context of their own business situations:

Use properties only when a property is appropriate, but do not expose data unnecessarily.

Use auto-implemented properties, instead of making a field public, unless there is a very good
reason not to.

Best Practices Related to Indexers


Help the students understand the best practices presented in this section. Ask students to consider these
best practices in the context of their own business situations:

Use a default property to access a data member that is part of a set. A default property is not a
method; if you are writing too much code in a default property, consider whether it would be
better implemented as a method.

Best Practices Related to Operators


Supplement or modify the following best practices for your own work situations:

Implement symmetric operators for commutable operations.

Do not modify the value of operands in an operator.

Define only meaningful operators.

Programming in Visual Basic with Microsoft Visual Studio 2010

Lab Review Questions and Answers


Lab A: Creating and Using Properties
Question: What is the syntax for declaring a property in an interface?
Answer: You specify the type and the property name, possibly prefixed with ReadOnly or
WriteOnly, as in the following example. [ReadOnly | WriteOnly] Property Name As
String.
Question: What is the significant difference between auto-implemented properties and
standard properties?
Answer: Auto-implemented properties are always read and write. Standard properties are
ReadOnly or WriteOnly.
Question: What happens if you attempt to write to a read only or write only autoimplemented property?
Answer: Your code will not compile.

Lab B: Creating and Using Default Properties


Question: Can you overload a default property in a child class?
Answer: Yes. Overloading a default property in a child class is one of the advantages of a
default property, compared to an array.
Question: What are some of the advantages of using a default property in your class?
Answer: You can access individual data members by using nonnumeric subscripts. You can
provide several overloads that take different subscripts (type) to access data by using
different types of parameters.

Lab C: Overloading Operators


Question: Can you declare an operator that is not shared?
Answer: No. In Visual Basic, operators are always shared. They do not operate on an instance
of an object; you must specify all the operands in your code.
Question: Can you change the multiplicity of an operator?
Answer: No. The multiplicity of the operators in Visual Basic is fixed. If you must perform
functionality that requires a change to the multiplicity of an operator, you should declare a
method instead.

10-17

Programming in Visual Basic with Microsoft Visual Studio 2010

11-1

Module 11
Decoupling Methods and Handling Events
Contents:
Lesson 1: Declaring and Using Delegates

Lesson 2: Using Lambda Expressions

Lesson 3: Handling Events

Module Reviews and Takeaways

13

Lab Review Questions and Answers

15

11-2

Programming in Visual Basic with Microsoft Visual Studio 2010

Lesson 1

Declaring and Using Delegates


Contents:
Question and Answers

Additional Reading

Programming in Visual Basic with Microsoft Visual Studio 2010

Question and Answers


Why Decouple an Operation from a Method?
Question: If you develop a class library and want to enable developers who write consuming
applications to run code after an asynchronous method call completes, how can you provide
this functionality?
Answer: You can expose a delegate in your class library that other developers can add
handlers to. You then invoke the delegate after the logic in your method completes.

Defining a Delegate
Question: Which of the following are valid scopes to define a delegate: the namespace
scope, the class scope, or the method scope?
Answer: You can define a delegate at either the namespace or the class scope. You cannot
define a delegate in a method.

Invoking a Delegate
Question: Why should you always check that a delegate is not null before you invoke it?
Answer: If a delegate does not reference any methods, it will return Nothing. If you attempt
to invoke a null delegate, your application will throw a NullReferenceException exception.

11-3

11-4

Programming in Visual Basic with Microsoft Visual Studio 2010

Additional Reading
Defining a Delegate
For more information about delegates, see Delegates (Visual Basic).

Invoking a Delegate
For more information about asynchronous programming, see Asynchronous Programming
Overview.

Programming in Visual Basic with Microsoft Visual Studio 2010

11-5

Lesson 2

Using Lambda Expressions


Contents:
Question and Answers

Additional Reading

11-6

Programming in Visual Basic with Microsoft Visual Studio 2010

Question and Answers


What Is a Lambda Expression?
Question: Can you define a lambda expression without using a delegate to reference the
expression?
Answer: No. If you could, you would not have any way to call the expression.

Variable Scope in Lambda Expressions


Question: If you reference an open database connection in a lambda expression, which
would normally go out of scope at the end of the method that defines the expression, what
happens to the database connection when the method completes?
Answer: The database connection remains open in case the lambda expression is invoked.
The resource is not released until all references to the lambda expression have been removed
(normally when the delegate goes out of scope).

Programming in Visual Basic with Microsoft Visual Studio 2010

Additional Reading
Defining Lambda Expressions
For more information about lambda expressions, see Lambda Expressions (Visual Basic).

11-7

11-8

Programming in Visual Basic with Microsoft Visual Studio 2010

Lesson 3

Handling Events
Contents:
Question and Answers

Additional Reading

10

Detailed Demonstration Steps

11

Programming in Visual Basic with Microsoft Visual Studio 2010

Question and Answers


What Is an Event?
Question: What is the difference between a publicly exposed instance of a delegate and a
publicly exposed event?
Answer: You can invoke a delegate from any consuming type, whereas you can only invoke
an event in the containing class or a derivative of it.
Using Events
Question: Can consuming classes raise an event?
Answer: No. An event can be raised only by the containing class or a class that inherits from
that class.
Best Practices for Using Events
Question: What is the naming convention for methods that encapsulate the logic associated
with raising an event?
Answer: The method should be named to match the event name, but prefixed with the word
On.

Using Events in Graphical Applications


Question: Can you add code to the DoWork event handler to update the user interface
directly?
Answer: No. The DoWork event handler does not run on the UI thread, so it cannot update
the user interface. Instead, it can marshal data back to the UI thread and raise an event on
the UI thread to update the user interface.

Demonstration: Using Events


Question: Why should you use the Protected modifier instead of the Public modifier as the
access modifier for an On method?
Answer: An On method is intended to raise the event. An event should only be raised by the
containing class of a derivative of that class. The Protected access modifier grants access to
the containing class and to classes that derive from it. If you use the Public access modifier,
any class that consumes the type could call the On method and raise the event.

11-9

11-10

Programming in Visual Basic with Microsoft Visual Studio 2010

Additional Reading
Declaring an Event
For more information about events, see Events (Visual Basic).

Using Events
For more information about the WithEvents modifier, see WithEvents (Visual Basic).
For more information about the Handles keyword, see Handles Clause (Visual Basic).
For more information about how to declare and raise events, see Walkthrough: Declaring and
Raising Events (Visual Basic).
For more information about handling events, see Walkthrough: Handling Events (Visual Basic).

Using Events in Graphical Applications


For more information about how to run an operation in the background, see How to: Run an
Operation in the Background.

Programming in Visual Basic with Microsoft Visual Studio 2010

11-11

Detailed Demonstration Steps


Demonstration: Disassembling a .NET Framework Assembly
Detailed demonstration steps
1.

Start Visual Studio 2010:

2.

3.

Click Start, point to All Programs, click Microsoft Visual Studio 2010, and then
click Microsoft Visual Studio 2010.

Open the Module 11, Demo1 starter solution:


a.

On the File menu, click Open Project.

b.

Browse to the D:\Demofiles\Mod11\Demo1\Starter folder, and then double-click


UsingEventsDemo.sln.

Open the Heartbeat.vb file, and then review the Heartbeat class:
a.

In Solution Explorer, double-click Heartbeat.vb, and then describe the Heartbeat class.

b.

Highlight the Start and Stop methods. Explain that the Start method creates a new thread
and on that thread runs a loop that increments a counter every three seconds. Explain that
the Stop method simply sets a flag for the loop to stop.

4.

Uncomment the HeartbeatEventArgs class. Explain how this class inherits from the EventArgs
class and defines a read-only property for the heartbeat count.

5.

Uncomment the code that defines an event named Beat. Explain that your class will raise this
event each time the heartbeat count is incremented.

6.

Uncomment the OnBeat method. Explain that this method raises the event. Remind students
that this is a best practice, and this method can be overridden in child classes.

7.

Uncomment the code in the Start method that raises the Beat event by using the OnBeat
method. Explain how you use the Me keyword as the first parameter and create a new instance
of the HeartbeatEventArgs class by using the current count as the second parameter.

8.

Open the MainWindow.xaml.vb file, and then review the event handlers for the Click events:

9.

a.

In Solution Explorer, right-click MainWindow.xaml, and then click View Code.

b.

Highlight the StartButton_Click and button2_Click methods.

Uncomment the code in the StartButton_Click method that adds an event handler for the Beat
event of the beat object.

10. Uncomment the beat_Beat method. Explain how this method handles the Beat event by
displaying a message box each time that event is raised. Highlight the use of the property from
the custom event arguments class.
11. Run the application:

Press Ctrl+F5.

12. Click Start.


13. Verify that the application works correctly. Highlight the message boxes when they appear (they
should appear every three seconds).

11-12

Programming in Visual Basic with Microsoft Visual Studio 2010

14. Close the application.


15. Close Visual Studio:

In Visual Studio, on the File menu, click Exit.

Programming in Visual Basic with Microsoft Visual Studio 2010

11-13

Module Reviews and Takeaways


Review questions
Question: When might it be inappropriate to use a lambda expression?
Answer: here are several answers; this question can be a good topic for discussion if time
permits. One important answer is that it is inappropriate if you must write the same lambda
expression on more than one occasionif this is the case, you should avoid code
duplication, create a named method, and use the named method on each occasion. In
addition, if the lambda expression becomes very long, it may be more readable and
otherwise clearer to create a named method; generally, lambda expressions should be kept
relatively short (although they may take a long time to run).
Question: How can you invoke a method asynchronously if it only natively supports being
called synchronously?
Answer: You can create a delegate with a signature that matches the method and then add
the method as a handler for the delegate. The delegate type includes BeginInvoke and
EndInvoke methods and other members that you can use to invoke any synchronous
method asynchronously.
Question: Can lambda expressions use variables declared outside the lambda expression?
Answer: Yes. However, doing so will often affect the life cycle of the variable. For example, a
variable defined in a method that would otherwise have gone out of scope will be persisted
until the lambda expression goes out of scope if used in the lambda expression. This can
unexpectedly increase the lifespan of a variable and potentially resource usage as a
consequence.

Best Practices
Best Practices Related to Using Delegates
Help the students understand the best practices presented in this section. Ask students to
consider these best practices in the context of their own business situations:

Use the delegate types defined in the .NET Framework instead of developing custom delegate
types wherever possible.

Use delegates to invoke synchronous methods asynchronously where appropriate; however, you
should not omit asynchronous methods from a type where you can implement the asynchronous
version of a method more efficiently than using the delegate syntax.

Best Practices Related to Using Lambda Expressions


Help the students understand the best practices presented in this section. Ask students to
consider these best practices in the context of their own business situations:

Only use a lambda expression if you use the method only once. If you are writing duplicate
lambda expressions, you should normally use a named method instead.

Do not change an object's state in a lambda expression. Wherever possible, you should write
lambda expressions that do not have side effects.

Avoid referencing variables defined outside the scope of the lambda expression.

Best Practices Related to Using Events

11-14

Programming in Visual Basic with Microsoft Visual Studio 2010

Help the students understand the best practices presented in this section. Ask students to
consider these best practices in the context of their own business situations:

Use the standard event signature.

Use a protected overridable method to raise an event.

Do not pass Nothing as a parameter when you raise an event.

Programming in Visual Basic with Microsoft Visual Studio 2010

Lab Review Questions and Answers


Question: If you declare an event, when should you use the EventArgs class?
Answer: You should use the EventArgs class only if you are sure that neither the current
version nor any future version will need to pass any data as an argument when the event is
raised. If there is a chance that you may need to pass an argument in the future, you should
use a class that inherits from the EventArgs class instead.
Question: What are the advantages of defining an On method to raise an event?
Answer: When you define an On method, you reduce code duplication; for example, code
that you run every time you raise an event needs to be written only once, and you then raise
the event by using the method. In addition to reducing code duplication, an On method
ensures that any classes that derive from your class can modify the behavior when the class
raises the event if the requirements change.
Question: What is the primary difference between exposing an instance of a delegate and
exposing an event?
Answer: If you expose an instance of a delegate, consuming applications can both subscribe
to the delegate and invoke the delegate. If you expose an event, consuming applications can
subscribe to the event, but they cannot raise the event (invoke the handler). Only the
containing class (or one that derives from it) can raise the event.
Question: When you define a lambda expression, what are the rules for using type inference
with input parameters?
Answer: The types must be able to be inferred from the delegate that references the
expression. If your lambda expression takes a different type (for example, where an implicit
conversion between the delegate type and the required type exists), you cannot use type
inference and must explicitly type the parameters. If you explicitly type a single parameter,
you must explicitly type all of the parameters for that lambda expression. You cannot
combine implicit and explicit type inference in a lambda expression.

11-15

Programming in Visual Basic with Microsoft Visual Studio 2010

Module 12
Using Collections and Building Generic Types
Contents:
Lesson 1: Using Collections

Lesson 2: Creating and Using Generic Types

Lesson 3: Defining Generic Interfaces and Understanding Variance

11

Lesson 4: Using Generic Methods and Delegates

14

Module Reviews and Takeaways

18

Lab Review Questions and Answers

19

12-1

12-2

Programming in Visual Basic with Microsoft Visual Studio 2010

Lesson 1

Using Collections
Contents:
Question and Answers

12-3

Additional Reading

12-4

Detailed Demonstration Steps

12-5

Programming in Visual Basic with Microsoft Visual Studio 2010

Question and Answers


What Is a Collection?
Question: You are developing an application that maintains a rolling buffer of 10 readings
taken by a device. Would you use an array or a collection to store the values?
Answer: You would normally use an array. If you did not know the size of the collection, a
collection may be more appropriate. However, the number of readings that you need to
store an array is more efficient, in addition to being type-safe.

Using Collection Classes


Question: Are collections type-safe?
Answer: No. Collections store items by using the System.Object type. When you retrieve an
item from a collection, you must cast it to the correct type. The compiler cannot verify that
your cast is correct at compile time; rather, at run time, your application will throw an
InvalidCastException exception if you attempt an invalid cast.
Question: When you use a For Each statement with a collection based on the SortedList
type, in what order will the For Each statement return items from the collection?
Answer: The For Each statement will order the items according to the key that is provided
for each key and value pair in the collection.
Question: Can you use a collection initializer with the Stack collection class?
Answer: No. The Stack collection class exposes Push and Pop methods to add and remove
items. To use a collection initializer, the class must expose an Add method.

Common Collection Classes


Question: When would you use a Hashtable collection?
Answer: When you need to store a large number of items that include a key and value pair.
You should not use a Hashtable collection for small collections because the overhead of
maintaining the Hashtable collection will exceed the gains compared to other collection
classes.

Demonstration: Using Collections


Question: What is the advantage of using the SortedList class compared to using a
multidimensional array?
Answer: The SortedList class enables you to add items to the collection, and it automatically
grows in size as you add more items. An array has a fixed size and will not grow when you
reach the maximum capacity. The SortedList class also enables you to retrieve items from
the collection by specifying the key. Using an array, you must use a numeric index to access
items in the array.

12-3

12-4

Programming in Visual Basic with Microsoft Visual Studio 2010

Additional Reading
Using Collection Classes
For more information about collection initializers, see the Object and Collection Initializers Overview
(Visual Basic) page.

Common Collection Classes


For more information about the common collection types, see the Commonly Used Collection Types
page.

Programming in Visual Basic with Microsoft Visual Studio 2010

12-5

Detailed Demonstration Steps


Demonstration: Using Collections
Detailed demonstration steps
1.

Start Microsoft Visual Studio 2010:

2.

3.

Click Start, point to All Programs, click Microsoft Visual Studio 2010, and then click
Microsoft Visual Studio 2010.

Open the Module 12, Demo1 starter solution:


a.

On the File menu, click Open Project.

b.

Browse to the D:\Demofiles\Mod12\Demo1\Starter folder, and then double-click


UsingCollectionsDemo.sln.

Open the Module1.vb file, and then review the Module1 module:

In Solution Explorer, double-click Module1.vb, and then describe the Module1 module
(which currently does nothing of any interest).

4.

Uncomment the code that creates a new SortedList collection named people.

5.

Uncomment the code that adds a Person object named Richard to the people collection. Explain
how this code uses an object initializer.

6.

Uncomment the code that creates a Person object named louisa.

7.

Uncomment the code that adds the louisa object to the people collection. Explain how this uses the
Add method to add an existing item to an existing collection.

8.

Uncomment the code that retrieves a Person object from the people collection by using the name as
an indexer. Highlight the cast from the Object type to the Person type.

9.

Uncomment the code that checks whether the personFromCollection field is Nothing and, if it is
not Nothing, writes the information to the screen.

10. Uncomment the code that iterates through every item in the people collection.
11. Run the application:

Press Ctrl+F5.

12. When the application pauses, highlight the data that is returned from the collection and displayed on
the screen, and then press Enter.
13. When the application pauses again, highlight that the details of two people are displayed on the
screen, and then press Enter.
14. Close the application.
15. Close Visual Studio:

In Visual Studio, on the File menu, click Exit.

12-6

Programming in Visual Basic with Microsoft Visual Studio 2010

Lesson 2

Creating and Using Generic Types


Contents:
Question and Answers

12-7

Additional Reading

12-8

Detailed Demonstration Steps

12-9

Programming in Visual Basic with Microsoft Visual Studio 2010

Question and Answers


What Are Generic Types?
Question: What are the benefits of using a generic class compared to a nongeneric class?
Answer: The benefits of using a generic class include ensuring compile-time type safety and
enabling you to omit casts in your applications.

Compiling Generic Types and Type Safety


Question: When the compiler compiles an application that uses a generic type, it generates
a concrete version of the generic class. How can you call the concrete version in your
application?
Answer: You use the generic class. You can never directly call the compiler-generated class;
you must call the generic class and the compiler will convert your method calls to use the
concrete class when it compiles the application.

Adding Constraints to Generic Types


Question: How can you ensure that when an instance of a generic class is created, a
reference type is used for the type parameter?
Answer: You use the Class keyword as the constraint.

Demonstration: Defining a Generic Type


Question: What happens if you attempt to use the wrong type when you call a method that
uses a generic type?
Answer: The code will not compile. The compiler ensures type safety when you use generic
types.

12-7

12-8

Programming in Visual Basic with Microsoft Visual Studio 2010

Additional Reading
What Are Generic Types?
For more information about generics, see the Generic Types in Visual Basic (Visual Basic) page.

Adding Constraints to Generic Types


For more information about constraints, see the Type List (Visual Basic) page.

Programming in Visual Basic with Microsoft Visual Studio 2010

12-9

Detailed Demonstration Steps


Demonstration: Defining a Generic Type
Detailed demonstration steps
1.

Start Visual Studio:

2.

3.

Click Start, point to All Programs, click Microsoft Visual Studio 2010, and then click
Microsoft Visual Studio 2010.

Open the Module 12, Demo2 starter solution:


a.

On the File menu, click Open Project.

b.

Browse to the D:\Demofiles\Mod12\Demo2\Starter folder, and then double-click


DefiningAGenericTypeDemo.sln.

Open the Printer.vb file, and then review the Printer class:

In Solution Explorer, double-click Printer.vb, and then describe the Printer class. The
Printer class is a generic class that takes a single type parameter named DocumentType.
The purpose of the class is to represent a printer that is capable of printing a specific type of
document.

4.

Uncomment the code that creates a new generic Queue object named printQueue by using the
DocumentType type parameter to specify the type of the Queue object. Explain how this collection
class stores items in a first-in, first-out (FIFO) manner.

5.

Uncomment the AddDocumentToQueue method. Explain how this method uses the generic type
parameter to define the types that can be used as a parameter.

6.

Uncomment the PrintDocuments method. Explain how this method removes items from the queue
and calls the Print method on each item.

7.

Open the Module1.vb file, and then review the Module1 module:

In Solution Explorer, double-click Module1.vb, and then describe the Module1 module. The
Module1 module currently creates three Report objects and three ReferenceGuide objects.
The Report and ReferenceGuide classes both implement the IPrintable interface, but are
not related in any other way.

8.

Uncomment the code that creates a new instance of the Printer class by specifying the Report type
and adds three reports to the print queue.

9.

Uncomment the code that calls the PrintDocuments method on the reportPrinter object. Explain
that this calls the method from the Printer class and removes each item from the print queue.

10. Uncomment the code that creates a new instance of the Printer class by specifying the
ReferenceGuide type and adds three reference guides to the print queue.
11. Uncomment the code that calls the PrintDocuments method on the referenceGuidePrinter object.
Explain that this calls the method from the Printer class and removes each item from the print queue.
12. Run the application:

Press Ctrl+F5.

13. Close the application.

12-10

Programming in Visual Basic with Microsoft Visual Studio 2010

14. Close Visual Studio:

In Visual Studio, on the File menu, click Exit.

Programming in Visual Basic with Microsoft Visual Studio 2010

Lesson 3

Defining Generic Interfaces and Understanding Variance


Contents:
Question and Answers

12-12

Additional Reading

12-13

12-11

12-12

Programming in Visual Basic with Microsoft Visual Studio 2010

Question and Answers


Defining Generic Interfaces
Question: How can you ensure that types that are used with a generic interface can be
compared?
Answer: Add a constraint by using the As keyword, which specifies that types that are used
with the generic interface implement the IComparable interface.

What Is Invariance?
Question: When you define a generic interface, by default, is it invariant, contravariant, or
covariant?
Answer: By default, generic interfaces are invariant.

Programming in Visual Basic with Microsoft Visual Studio 2010

12-13

Additional Reading
What Is Invariance?
For more information about variant generic interfaces, see the Creating Variant Generic Interfaces (C# and
Visual Basic) page.

12-14

Programming in Visual Basic with Microsoft Visual Studio 2010

Lesson 4

Using Generic Methods and Delegates


Contents:
Question and Answers

12-15

Detailed Demonstration Steps

12-16

Programming in Visual Basic with Microsoft Visual Studio 2010

Question and Answers


What Are Generic Methods and Delegates?
Question: When should you use a generic method?
Answer: You should use a generic method when you need to define a method that acts on
several other unrelated types, and you need to ensure type safety. For example, you may use
a type parameter with a method that compares two values. You could use a single type
parameter for two method parameters. This ensures that the two parameters are always the
same type when the method is invoked, but provides the flexibility to use the same method
with several different types.

Using the Generic Delegate Types Included in the .NET Framework


Question: When might you choose not to use the generic delegates that the .NET
Framework provides?
Answer: This question is designed to stimulate discussion among the students, so there is no
definitive answer. Possible reasons include if you need to define a delegate that does not
support variance.

Defining a Generic Method


Question: Can you use variance when you define a generic method?
Answer: No. You can only use variance when you define a generic interface. However, you
can specify a generic method in a generic interface that uses variance.

Using Generic Methods


Question: When you define a generic method, how many type parameters can you specify?
Answer: You can specify as many type parameters as you require; there is no limit.

Demonstration: Defining a Generic Delegate


Question: How does defining a generic delegate differ from defining a nongeneric delegate?
Answer: When you define a generic delegate, you add type parameters and use the type
parameters in the delegate signature. There is no other difference.

12-15

Programming in Visual Basic with Microsoft Visual Studio 2010

12-16

Detailed Demonstration Steps


Demonstration: Defining a Generic Delegate
Detailed demonstration steps
1.

Start Visual Studio:

2.

3.

Click Start, point to All Programs, click Microsoft Visual Studio 2010, and then click
Microsoft Visual Studio 2010.

Open the Module 12, Demo3 starter solution:


a.

On the File menu, click Open Project.

b.

Browse to the D:\Demofiles\Mod12\Demo3\Starter folder, and then double-click


DefiningAGenericDelegateDemo.sln.

Open the Printer.vb file, and then review the Printer class:

In Solution Explorer, double-click Printer.vb, and then describe the Printer class. The
Printer class is a generic class that takes a single type parameter named DocumentType.
The purpose of the class is to represent a printer that is capable of printing a specific type of
document.

4.

Uncomment the code that defines the DocumentAddingToQueueDelegate type. Highlight that the
delegate includes a type parameter.

5.

Uncomment the code that defines the DocumentAddingToQueue event. Highlight that the event
uses the generic delegate that you defined in the previous step.

6.

Uncomment the OnDocumentAddingToQueue method and explain how this method is used to
raise the event.

7.

In the AddDocumentToQueue method, uncomment the code that raises the


OnDocumentAddingToQueue event and uses the response to determine whether to add the item
to the print queue.

8.

Open the Module1.vb file, and then review the Module1 module:

9.

In Solution Explorer, double-click Module1.vb, and then describe the Module1 module.

Uncomment the code that adds a handler for the OnDocumentAddingToQueue event, and
uncomment the handler method. Explain how the handler method displays a message box and
returns a value based on the response.

10. Run the application:

Press Ctrl+F5.

11. In the Reference Guide Printing dialog box, click OK.


12. In the Reference Guide Printing dialog box, click Cancel.
13. In the Reference Guide Printing dialog box, click OK.
14. When the application pauses, verify that only two documents have printed, because you canceled the
second document.
15. Close the application.

Programming in Visual Basic with Microsoft Visual Studio 2010

12-17

16. Open the Printer.vb file:

In Solution Explorer, double-click Printer.vb.

17. Uncomment the DocumentPrintedEventArgs generic class, and explain how this class inherits from
the EventArgs class and exposes a Document property. Explain that this will be used in an event that
will notify subscribers that a document has been printed, and provide the document that printed as
an argument.
18. Uncomment the code that defines the DocumentPrinted event by using the Action generic
delegate. Explain how this event uses an instance of the Printer generic class and an instance of the
DocumentPrintedEventArgs generic class as parameters.
19. Uncomment the OnDocumentPrinted method, and explain how this method raises the
DocumentPrinted event.
20. In the PrintDocuments method, uncomment the code that calls the OnDocumentPrinted method,
and explain how this raises the DocumentPrinted event whenever a document is printed.
21. Open the Module1.vb file, and then review the Module1 module:

In Solution Explorer, double-click Module1.vb.

22. Uncomment the code that adds a handler for the DocumentPrinted event, and uncomment the
handler method. Explain how the handler method displays a message box.
23. Run the application:

Press Ctrl+F5.

24. In the Reference Guide Printing dialog box, click OK.


25. In the Reference Guide Printing dialog box, click Cancel.
26. In the Reference Guide Printing dialog box, click OK.
27. When the application pauses, verify that only two documents printed, because you canceled the
second document, and then press Enter.
28. In the Report Printed dialog box, click OK three times.
29. When the application pauses, verify that only three documents printed.
30. Close the application.
31. Close Visual Studio:

In Visual Studio, on the File menu, click Exit.

Programming in Visual Basic with Microsoft Visual Studio 2010

12-18

Module Reviews and Takeaways


Review questions
Question: What are the main advantages of using a collection class instead of an array?
Answer: Possible answers include:

Collections automatically grow when you add items, whereas arrays do not.

You can only access an array by index, whereas you can use keys to access members
of a collection.

Question: How do generic collection classes differ from nongeneric collection classes?
Answer: Generic collection classes are strongly typed and therefore prevent run-time cast
exceptions; non-generic classes use the object type, so they risk run-time errors.
Question: When would you use a generic type, instead of a nongeneric type?
Answer: You use generic types when you need to define a wrapper or provide functionality
for unrelated and possibly unknown types.

Best Practices Related to Collections

Use collections, instead of arrays, where you do not know the size of the collection in advance.

Use Hashtable objects for large key-value pair collections, but avoid them for smaller collections.

Best Practices Related to Generic Types

Use generic types wherever possible to improve type safety.

Use constraints on generic types to provide control over types that are used with your generic classes.

Best Practices Related to Generic Methods and Delegates

Use the Action and Func generic delegates, instead of custom delegates, wherever possible.

Programming in Visual Basic with Microsoft Visual Studio 2010

Lab Review Questions and Answers


Lab A: Using Collections
Question: In the lab, you used a very simple hash to add items to the Hashtable object.
How could you create a more complex hash?
Answer: You could use the classes in the System.Security.Cryptography namespace to
generate a hash value.

Lab B: Building Generic Types


Question: In the lab, you defined a generic interface with a type parameter. How did you
constrain the types that can be used with a class that implements this interface?
Answer: You used the As keyword and specified that the type must implement the
IComparable interface.
Question: In the lab, you used the name TItem for the type parameter of the Tree class, and
the name TreeItem for the shared generic method in the class. Why did you not use the
same name in both instances?
Answer: The type parameter for the class is still in scope for the generic method, so using
the same type name would have introduced ambiguity. Also, if you attempt to use a type
parameter defined at the class level in a shared method, the type parameter will return
Nothing and throw an exception. You should only re-use type parameter names where each
previous use is out of scope.

12-19

Programming in Visual Basic with Microsoft Visual Studio 2010

Module 13
Building and Enumerating Custom Collection Classes
Contents:
Lesson 1: Implementing a Custom Collection Class

Lesson 2: Adding an Enumerator to a Custom Collection Class

Module Reviews and Takeaways

10

Lab Review Questions and Answers

11

13-1

13-2

Programming in Visual Basic with Microsoft Visual Studio 2010

Lesson 1

Implementing a Custom Collection Class


Contents:
Question and Answers

13-3

Additional Reading

13-5

Programming in Visual Basic with Microsoft Visual Studio 2010

Question and Answers


What Are Custom Collection Classes?
Question: When might you develop a custom collection class?
Answer: You might develop a custom collection class when you need to implement
semantics that are not provided by the collection classes that the .NET Framework base class
library provides.

Generic Collection Interfaces in the .NET Framework


Question: When you develop a custom collection class, which interface must you always
implement?
Answer: You should always implement the ICollection(Of T) interface when you develop a
custom collection class. Other interfaces may also be appropriate, such as the IList(Of T)
interface, but you should implement the ICollection(Of T) interface in every custom
collection class.

Implementing a Simple Custom Collection Class


Question: You develop an application that stores data in a file in a custom format. The file
structure is predefined and uses a structure that is similar to, but not the same as, XML. Data
that is stored in the file is stored in a specified order, and the application needs to both read
and write to the file. How can you use a custom collection class to make it easier to use the
data file in the application?
Answer: You can develop a custom collection class that uses the file as the data store. You
can implement the standard interfaces in your collection class, including the IList(Of T)
interface, because you are developing a sequential collection. Applications can then use your
collection type to read and write data to the file by using standard Visual Basic programming
constructs; they do not require any knowledge of the underlying file or its structure.

Implementing a Dictionary Collection Class


Question: You develop a dictionary collection class and implement the IDictionary(Of
TKey, TValue) interface. You must use the underlying Dictionary(Of TKey, TValue) class as
an internal data store. When you implement the CopyTo method that the interface requires,
you discover that the generic dictionary class does not expose a public CopyTo method. The
generic dictionary class implements the CopyTo method that the interface defines explicitly.
Implementing the interface explicitly avoids exposing the CopyTo method when referencing
a collection by using the Dictionary(Of TKey, TValue) type. When might you use this
approach in collections that you develop?
Answer: Implementing interface members explicitly is a convenient way to hide methods
that do not make sense in terms of your collection. In the case of the dictionary class, it does
not make sense to use the CopyTo method on a dictionary collection of keys and values;
however, if you cast the dictionary collection as an instance of the ICollection(Of T)
interface, it makes more sense to copy to an array, because you will copy instances of the
KeyValuePair(Of TKey, TValue) class, rather than the keys and values individually.
Another example is the Add method. The ICollection(Of T) interfaces requires an Add
method, but in many collections, this does not make sense; for example, you use the Queue
class to enqueue and dequeue an item rather than add and remove it. When you implement

13-3

13-4

Programming in Visual Basic with Microsoft Visual Studio 2010

the Add method explicitly, you can hide the method, and applications that refer to your
collection by using an interface reference that will work correctly. An interface member that
is implemented explicitly can still be accessed and should be implemented fully.

Programming in Visual Basic with Microsoft Visual Studio 2010

Additional Reading
Generic Collection Interfaces in the .NET Framework
For more information about the ICollection(Of T) interface, see the ICollection(Of T) Interface page.
For more information about the IList(Of T) interface, see the IList(Of T) Interface page.
For more information about the IDictionary(Of TKey, TValue) interface, see the IDictionary(Of TKey,
TValue) Interface page.

13-5

13-6

Programming in Visual Basic with Microsoft Visual Studio 2010

Lesson 2

Adding an Enumerator to a Custom Collection Class


Contents:
Question and Answers

13-7

Additional Reading

13-9

Programming in Visual Basic with Microsoft Visual Studio 2010

Question and Answers


What Is an Enumerator?
Question: An enumerator provides read-only access to items in a collection. Why would it be
inappropriate to permit write access to items that are accessed by using an enumerator?
Answer: This question is designed to stimulate discussion among the students, so there is no
definitive answer. One problem with permitting write access to an enumerator is that
enumerators often return data in a specific order. Changing the value of an item in the
collection may cause the item to be out of order in the collection. This may cause
unexpected side effects.

What Is the IEnumerable(Of T) Interface?


Question: How does the For Each statement use the IEnumerable(Of T)interface?
Answer: The For Each statement uses the GetEnumerator method that the
IEnumerable(Of T) interface exposes to retrieve the default enumerator for a type when no
other enumerator is explicitly specified.

What Is the IEnumerator(Of T) Interface?


Question: How does the MoveNext method indicate to the caller that advancing any
further would result in an invalid state because the enumerator has reached the end of the
collection?
Answer: The MoveNext method returns False when it has reached the end of the collection.

Implementing an Enumerator Manually


Question: In the code example on the slide that is associated with this topic, the Get
procedure checks that the value of the pointer variable is not 1 before it returns a value. 1
is the initial value for the pointer. Why would 1 be the initial value, and why does the Reset
method set the pointer back to 1?
Answer: The value 1 will throw an exception if you attempt to use it as an index in an array.
If you increment 1, you get 0, which is the index of the first item in an array. When you use
an enumerator, the enumerator should always start in an invalid state, and you should call
the MoveNext method before you access the Current property for the first time. Setting the
pointer to 1 ensures that after you have called the MoveNext method for the first time, the
enumerator is ready to return the first item from the collection. The Reset method should
return the enumerator to its initial invalid state, so it must set the value to 1. If the Reset
method set the value to 0, when the MoveNext method was invoked, it would advance the
enumerator to index 1; this is the second item in the collection, and the first item (index 0)
would be skipped.

Implementing a Reverse Enumerator by Using an Iterator


Question: How can you use an iterator in conjunction with a property to expose an
enumerator?
Answer: You can expose a property that returns an instance of the IEnumerable(Of T)
interface. You implement the Get procedure for the property by using an iterator that uses

13-7

13-8

Programming in Visual Basic with Microsoft Visual Studio 2010

return items from your collection in the required order. You can then use the property where
you would use an enumerator, for example, in a For Each statement.

Programming in Visual Basic with Microsoft Visual Studio 2010

13-9

Additional Reading
What Is the IEnumerable(Of T) Interface?
For more information about the IEnumerable(Of T) interface, see the IEnumerable(Of T) Interface page.

What Is the IEnumerator(Of T) Interface?


For more information about the IEnumerator(Of T) interface, see the IEnumerator(Of T) Interface page.

Programming in Visual Basic with Microsoft Visual Studio 2010

13-10

Module Reviews and Takeaways


Review questions
Question: What are the advantages of developing a custom collection class?
Answer: A custom collection class enables you to use a custom internal representation for
data that is based on how you need to represent the data, and it enables you to use custom
sorting.
Question: You want to ensure that your custom collection class can be enumerated by using
a For Each statement, and you need to support collection initializers with your type. What
steps would you take to achieve this?
Answer: Implement generic interfaces for collection classes such as the ICollection interface,
the IList interface, or the IDictionary interface.
Question: You develop a custom collection class. Applications that consume your class need
to iterate over the data that is stored in your collection class in several different ways and
obtain data in different orders. How would you implement this functionality in a custom
collection class, and how would you provide a default order for iterating over the data in
your collection class?
Answer: Add properties or methods to the class that return instances of the
IEnumerable(Of T) interface; you can use each instance to return data that is ordered
according to specific requirements. To implement a default order, implement the
IEnumerable(Of T) interface in your type and expose a GetEnumerator method. The
enumerator that the GetEnumerator method returns is the default enumerator that is used
with your type when no other enumerator is specified.

Best Practices Related to Developing Custom Collection Classes

Implement the appropriate interfaces to ensure that your class is compatible with the standard
collection-handling constructs in Visual Basic.

Always use the generic interfaces in preference to nongeneric interfaces when you develop a custom
collection class.

Best Practices Related to Implementing Enumerators

Implement the IEnumerable(Of T) interface to define a default enumerator for your type.

Expose additional enumerators by using a property or a method in your custom collection class.

Implement enumerators by using iterators to minimize the possibility of errors in your code.

Programming in Visual Basic with Microsoft Visual Studio 2010

Lab Review Questions and Answers


Question: In the lab, you implemented the IList(Of T) interface. When would you use the
IList(Of T) interface in a custom class?
Answer: You would use the IList(Of T) interface when you develop a custom collection class
to store items in a linear collection that you can access by using an index.

13-11

Programming in Visual Basic with Microsoft Visual Studio 2010

Module 14
Using LINQ to Query Data
Contents:
Lesson 1: Using the LINQ Extension Methods and Query Operators

Lesson 2: Building Dynamic LINQ Queries and Expressions

Module Reviews and Takeaways

10

Lab Review Questions and Answers

11

14-1

14-2

Programming in Visual Basic with Microsoft Visual Studio 2010

Lesson 1

Using the LINQ Extension Methods and Query Operators


Contents:
Question and Answers

14-3

Additional Reading

14-5

Programming in Visual Basic with Microsoft Visual Studio 2010

Question and Answers


What Is the Purpose of LINQ?
Question: Briefly summarize the purpose of LINQ.
Answer: The purpose of LINQ is to simplify the development of data-processing logic by
providing features that abstract the mechanisms that are required to query data from the
code in your applications.

Querying Data and Building a Result Set


Question: In the following code example, what does the employeeDetails array contain?
Dim employeeDetails = employees.Select(Function(empl) empl.ID)

Answer: A reference to an enumerable collection of employee IDs.

Filtering Data
Question: What does the result object represent in the following code example?
Dim customers As
{
New Customer
New Customer
New Customer
New Customer
New Customer
New Customer
New Customer
}

IEnumerable(Of Customer) =
With
With
With
With
With
With
With

{.FirstName
{.FirstName
{.FirstName
{.FirstName
{.FirstName
{.FirstName
{.FirstName

=
=
=
=
=
=
=

"Luka", .LastName = "Abrus", .Age = 41},


"Syed", .LastName = "Abbas", .Age = 23},
"Keith", .LastName = "Harris", .Age = 59},
"David", .LastName = "Pelton", .Age = 25},
"John", .LastName = "Peoples", .Age = 37},
"Toni", .LastName = "Poe", .Age = 29},
"Jeff", .LastName = "Price", .Age = 74}

Dim result = customers.Where(Function(cust) cust.LastName = "Poe")

Answer: The result object represents a reference to an IEnumerable(Of Customer) object


that contains all the customers who have a last name of Poe.

Ordering Data
Question: Which extension method would you use to sort an array of strings into
descending order?
Answer: The OrderByDescending extension method.

Grouping Data and Performing Aggregate Calculations


Question: In the following code example, what does the result object contain?
Dim customers As
{
New Customer
New Customer
New Customer
New Customer
New Customer
New Customer
New Customer
}

IEnumerable(Of Customer) =
With
With
With
With
With
With
With

{.FirstName
{.FirstName
{.FirstName
{.FirstName
{.FirstName
{.FirstName
{.FirstName

=
=
=
=
=
=
=

"Luka", .LastName = "Abrus", .Age = 41},


"Syed", .LastName ="Abbas", .Age = 23},
"Keith", .LastName ="Harris", .Age = 59},
"David", .LastName = "Pelton", .Age = 41},
"John", .LastName = "Peoples", .Age = 23},
"Toni", .LastName = "Poe", .Age = 29},
"Jeff", .LastName = "Price", .Age = 23}

14-3

14-4

Programming in Visual Basic with Microsoft Visual Studio 2010

Dim result =
customers.Count(Function(cust) cust.LastName.StartsWith("P"))

Answer: The result object contains the numeric value 4.

Joining Data from Different Data Sets


Question: In the following code example, what does the result object contain?
Dim phones As IEnumerable(Of CellPhone) = {
New CellPhone With {.ID = 1, .Make = "...", .Model = "...", .NetworkID = 1},
New CellPhone With {.ID = 2, .Make = "...", .Model = "...", .NetworkID = 1},
New CellPhone With {.ID = 3, .Make = "...", .Model = "...", .NetworkID = 2}
}
Dim networks As IEnumerable(Of CellPhoneNetwork) = {
New CellPhoneNetwork With {.ID = 1, .Name = "..."},
New CellPhoneNetwork With {.ID = 2, .Name = "..."}
}
Dim result = phones.Select(Function(p) p).Join(
networks,
Function(p) p.NetworkID,
Function(n) n.ID,
Function(p, n) New With {p.Make, p.Model, n.Name})

Answer: The result object contains an enumerable result set that contains a new type that
models the make and model of the cell phone, and the network name.

Using Visual Basic LINQ Query Operators


Question: In the following code examples, are both queries equivalent?
Dim payments As IEnumerable(Of Double) =
{232.12, 8378.53, 66.01, 4312.11, 156.00}
Dim queryOperatorResult =
(From payment in payments
Where payment > 100 AndAlso payment < 500
Select payment).Max()
Dim extensionMethodResult =
payments.Where(Function(payment) payment > 100 AndAlso payment < 500).Max()

Answer: Yes, both code examples produce the same result of 232.12.

Deferred and Early Evaluation of Queries


Question: In your application, you construct a LINQ query to retrieve all the employee
records from a database. In your code, after the LINQ query, you add a For Each statement
to iterate through each record. You start to debug and step over the LINQ query and then
pause before you enter the For Each statement. You then make a change to one of the
employee records in the database. Finally, you return to the Microsoft Visual Studio
debugger and continue to step into the For Each statement. Will the change that you made
to the employee record be visible when you iterate through the results?
Answer: Yes. The change will be visible because the LINQ query is not evaluated until the
For Each statement implicitly invokes the GetEnumerator method.

Programming in Visual Basic with Microsoft Visual Studio 2010

14-5

Additional Reading
What Is the Purpose of LINQ?
For more information about LINQ, see the Language-Integrated Query (LINQ) page.

Querying Data and Building a Result Set


For more information about LINQ, see the Introduction to LINQ in Visual Basic page.

Using Visual Basic LINQ Query Operators


For more information about LINQ query operators, see the Basic Query Operations (Visual Basic) page.

Deferred and Early Evaluation of Queries


For more information about LINQ queries and deferred execution, see the LINQ Query Samples - Query
Execution page.

14-6

Programming in Visual Basic with Microsoft Visual Studio 2010

Lesson 2

Building Dynamic LINQ Queries and Expressions


Contents:
Question and Answers

14-7

Additional Reading

14-9

Programming in Visual Basic with Microsoft Visual Studio 2010

14-7

Question and Answers


What Is a Dynamic LINQ Query?
Question: When might you use a dynamic LINQ query, instead of a shared LINQ query?
Answer: You might use a dynamic LINQ query if you do not know the full details of the
query when you develop the application.

What Is an Expression Tree?


Question: How can you extend the tree in the following diagram to satisfy the expression
(o.x > 3 AndAlso o.y> 6) OrElse o. y > 20?

/
/

/
>

AndAlso
/
\
-------------------

\
\
/
\
Member: o.x Constant: 3

\
>
/
\
/
\

/
\
Member: o.y Constant: 6

Answer: You can add an extra branch to the tree, as the following diagram shows.

>

/
AndAlso
/
\
---------------------------

/
Member: o.x

OrElse
/
\
-------------------

\
Constant: 3

/
Member: o.y

/
/
Member: o.y

\
>

\
/

>

\
Constant: 20

\
Constant: 6

Expression Types
Question: How would you define an expression that checks whether a member named x is
equal to the constant value 24?
Answer: Create a Member Expression object to represent the member x and a Constant
Expression object to represent the constant value 24. You would then combine the two
expressions into a BinaryExpression expression by using the shared Equal method.

Obtaining Type Information at Run Time


Question: What is the result of calling the GetProperty method on an instance of the Type
class that represents the String type and providing the string "ToString" as the argument?
Answer: Although the String type does contain a member named ToString, the member is
a method, not a property, so the GetProperty method will return Nothing. If you attempt to

14-8

Programming in Visual Basic with Microsoft Visual Studio 2010

use the MemberInfo object, your application may throw a NullReferenceException


exception.

Compiling and Running a Dynamic LINQ Query


Question: What is the purpose of the Compile method?
Answer: The Compile method converts an expression tree into an executable lambda
expression. You can use the lambda expression as a handler for a delegate or invoke the
expression by using dynamic invocation.

Programming in Visual Basic with Microsoft Visual Studio 2010

Additional Reading
What Is an Expression Tree?
For more information about expression trees, see the Expression Trees (C# and Visual Basic) page.

Expression Types
For more information about the expression types in the System.Linq.Expressions namespace, see the
System.Linq.Expressions Namespace page.
For more information about the Expression class, see the Expression Class page.

Compiling and Running a Dynamic LINQ Query


For more information about using expression trees to build dynamic queries, see the How to: Use
Expression Trees to Build Dynamic Queries (C# and Visual Basic) page.

14-9

Programming in Visual Basic with Microsoft Visual Studio 2010

14-10

Module Reviews and Takeaways


Review questions
Question: Which query operator would you use to implement filtering functionality on an
enumerable collection?
Answer: The Where query operator
Question: Which extension method would you use to remove duplicate values from an
enumerable collection?
Answer: The Distinct extension method
Question: How can you force early evaluation of a LINQ query?
Answer: By calling a method such as ToList or ToArray
Question: When would you use an expression tree in an application?
Answer: You would use an expression tree in an application when you need the application
to be highly flexible. An expression tree represents a lambda expression, and you can build
the expression tree based on the requirements at run time. You can then compile the
expression tree into an executable lambda expression that you can use anywhere that you
would normally use a lambda expression; this includes invoking the lambda expression
dynamically if you require it.

Best Practices Related to Using LINQ

Use LINQ queries rather than manually writing your own code to retrieve data and to help reduce
dependencies that your applications have on the structure that data sources use.

Use anonymous types to model the data that queries return, instead of creating new types.

Best Practices Related to Using Dynamic LINQ

Use dynamic LINQ queries where you require flexibility rather than developing several variants of a
query, which risks introducing errors and duplicate code.

Use the Type and MemberInfo classes to reference types and type members. Use the GetType
method and the Get methods (such as GetProperty) minimally to avoid excessive performance
issues.

Programming in Visual Basic with Microsoft Visual Studio 2010

Lab Review Questions and Answers


Question: In Exercise 1 of the lab, did the application perform deferred or early evaluation of
the LINQ query?
Answer: Deferred evaluation. The query was evaluated in a For Each statement.
Question: In Exercise 2, which shared method did you use to construct an expression tree
that represented a complete lambda expression?
Answer: The shared Expression.Lambda method

14-11

Programming in Visual Basic with Microsoft Visual Studio 2010

15-1

Module 15
Integrating Visual Basic Code with Dynamic Languages and
COM Components
Contents:
Lesson 1: Integrating Visual Basic Code with Ruby and Python

Lesson 2: Accessing COM Components from Visual Basic

Module Reviews and Takeaways

10

Lab Review Questions and Answers

11

15-2

Programming in Visual Basic with Microsoft Visual Studio 2010

Lesson 1

Integrating Visual Basic Code with Ruby and Python


Contents:
Question and Answers

Additional Reading

Detailed Demonstration Steps

Programming in Visual Basic with Microsoft Visual Studio 2010

Question and Answers


What Is the Dynamic Language Runtime?
Question: What is the purpose of the DLR?
Answer: The DLR enables you to integrate components and technologies that perform runtime type checking into a Visual Basic application. The DLR uses binders to determine the
type information for a dynamic component at run time, to resolve and dispatch method calls
to a dynamic component, and to marshal and unmarshal data between the common
language runtime (CLR) and the dynamic component.

Invoking and Using a Dynamic Object


Question: Why do you think that you cannot pass a lambda expression as an argument to a
method of a dynamic object?
Answer: The Visual Basic compiler needs to be able to determine, at compile time, the type
that a lambda expression returns. The type information for parameters of methods for
dynamic objects is not available until runtime.

15-3

15-4

Programming in Visual Basic with Microsoft Visual Studio 2010

Additional Reading
What Is the Dynamic Language Runtime?
For more information about the DLR, see the Dynamic Language Runtime Overview page.

Using Dynamic Types


For more information about the dynamic objects, see the Working with Dynamic Objects (Visual Basic)
page.

Programming in Visual Basic with Microsoft Visual Studio 2010

15-5

Detailed Demonstration Steps


Demonstration: Calling Python Code from Visual Basic
Detailed demonstration steps
1.

1.

Open the Python file, CustomerDB.py, in the D:\Demofiles\Mod15 folder:


a.

Using Windows Explorer, browse to the D:\Demofiles\Mod15 folder.

b.

Right-click CustomerDB.py, and then click Open.

c.

In the Windows dialog box, select the Select a program from a list of installed programs
option, and then click OK.

d.

In the Open with dialog box, expand Other Programs, click Notepad, and then click OK.

Walk through the code. Point out the following items in the Python file:

The Customer class, which models a customer. The __init__ method is the constructor. The
__str__ method returns a string representation of the customer.

The CustomerDB class, which acts as a container for a collection of customers. The __init__
method initializes a list to hold customers. The storeCustomer method adds a customer to
the list. The getCustomer method retrieves a customer from the list, and the __str__ method
returns the entire list as a formatted string.

The GetNewCustomer method, which is a factory method for creating new Customer
objects.

The GetCustomerDB method, which is a factory method for creating CustomerDB


collection objects.

2.

Close the Python file.

3.

Start Visual Studio:

4.

5.

Click Start, point to All Programs, click Microsoft Visual Studio 2010, and then click
Microsoft Visual Studio 2010.

Open the PythonInteroperability solution in the D:\Demofiles\Mod15 folder:


a.

On the File menu, click Open Project.

b.

Browse to the D:\Demofiles\Mod15 folder, and then double-click


PythonInteroperability.sln.

Display the code for the project:

In Solution Explorer, expand the PythonInteroperability project, and then double-click


Module1.vb.

6.

Walk through the code in the Main method. Point out the following items:

7.

The CreateRuntime method of the Python class, which is used to create the Python runtime.

The UseFile method that references the CustomerDB.py file.

The statement that calls the GetNewCustomer method to create a new Python Customer
object and store the reference in a variable that is declared as Object.

15-6

Programming in Visual Basic with Microsoft Visual Studio 2010

8.

9.

The statement that calls the GetCustomerDB method to create a new instance of the
CustomerDB collection class. The value is returned into a variable that is declared as Object.

The statement that calls the storeCustomer method to add the Customer object to the
CustomerDB collection. The value is stored in a third variable that is declared as Object.

The statements that call the GetNewCustomer method to create a second customer and the
storeCustomer method to add this Customer object to the CustomerDB collection.

The Console.WriteLine statement that displays the CustomerDB object. Mention that this
statement implicitly calls the ToString method to render the object as a string, which is in
turn converted into a call to the __str__ method of the CustomerDB object.

Show the references that the solution uses:


a.

In Solution Explorer, click PythonInteroperability, click Show All Files, and then expand
References.

b.

Point out the references to the IronPython and Microsoft.Scripting assemblies, which
together provide access to the IronPython runtime.

Build and run the application:


a.

On the Build menu, click Build Solution.

b.

Press Ctrl+F5.

c.

Verify that the application generates the following output:


Testing Python
Customers
ID: 100 Name: Fred

Telephone: 888

ID: 101 Name: Sid

Telephone: 999

10. Close the console window.


11. Close Visual Studio.

Programming in Visual Basic with Microsoft Visual Studio 2010

Lesson 2

Accessing COM Components from Visual Basic


Contents:
Question and Answers

Additional Reading

15-7

15-8

Programming in Visual Basic with Microsoft Visual Studio 2010

Question and Answers


Interoperating with COM from a Visual Basic Application
Question: Why is it necessary to create an RCW to invoke a COM component from a Visual
Basic application?
Answer: COM components run in unmanaged space and are not controlled by the CLR. The
RCW is responsible for instantiating the COM component and destroying it when the Visual
Basic application has finished with it. The RCW also acts as a proxy for the COM object,
calling methods on the COM object when directed by the Visual Basic application and
converting data between the formats that COM and the CLR expect.

Creating a COM Interop Assembly


Question: Why are PIAs important?
Answer: PIAs are important because they provide unique type identity. The PIA distinguishes
the verified type definitions that the publisher of a COM component signs from possible fake
or malicious definitions provided by other interop assemblies.

Instantiating a COM Component by Using a Runtime Callable Wrapper


Question: What is the difference between instantiating a Visual Basic object and a COM
object in a Visual Basic application?
Answer: To instantiate a Visual Basic object, you explicitly invoke the constructor for the
corresponding Visual Basic class and assign the result to a variable of the same type or of an
interface that the type implements. To instantiate a COM object, you invoke a constructor for
the managed wrapper around a COM interface that a COM coclass implements. This
managed wrapper is defined in the RCW for the COM component.

Calling Methods on a COM Object


Question: If you omit an argument to a COM method, what value does RCW use as the
default?
Answer: The Type.Missing value.

Deploying Without a Primary Interop Assembly


Question: If you specify PIA-less deployment, when you deploy an application that uses a
COM component, is it still necessary to deploy the COM component, too?
Answer: Yes. PIA-less deployment only embeds information about the interop assembly into
the application assembly. It is still necessary to deploy the COM component that the interop
assembly references.

Programming in Visual Basic with Microsoft Visual Studio 2010

Additional Reading
Interoperating with COM from a Visual Basic Application
For more information about marshaling COM data types, see the COM Data Types page.

Creating a COM Interop Assembly


For more information about using the Tlbimp utility, see the Tlbimp.exe (Type Library Importer) page.

15-9

Programming in Visual Basic with Microsoft Visual Studio 2010

15-10

Module Reviews and Takeaways


Review questions
Question: What is the difference between an interop assembly and an RCW?
Answer: An interop assembly contains the definitions of the types and interfaces that a COM
component exposes. The CLR uses the interop assembly to create an RCW when an
application runs. The RCW acts as a proxy to the COM component for the application.

Best Practices Related to Integrating Visual Basic Code with Dynamic


Languages

Program defensively. Do not assume when you build an application that uses scripts that are based
on dynamic languages that those scripts will be well-behaved. Be prepared to catch and handle
exceptions that scripts cause.

Be prepared to catch and handle exceptions that are caused by missing scripts or unexpected versions
of the runtime for the dynamic language.

Only use scripts from trusted sources.

Best Practices Related to Accessing COM Components from Visual Basic

Ensure that any COM components that an application uses are installed and available on the
computer that runs your application. Be prepared to catch and handle exceptions that missing COM
components cause.

Use PIA-less deployment.

Only use COM components that trusted sources provide.

Programming in Visual Basic with Microsoft Visual Studio 2010

Lab Review Questions and Answers


Question: Which component is responsible for translating Visual Basic method calls to a
Python object into Python method calls?
Answer: The Python binder.
Question: Which component is responsible for translating values that a Python method
returns into a format that a Visual Basic application can use?
Answer: The Python binder (again).
Question: How did you create the interop assembly that your application used to interact
with Office Excel?
Answer: You did not create the interop assembly. You added a reference to the PIA that
Microsoft providesit is supplied with Office Excel.

15-11

15-12

Programming in Visual Basic with Microsoft Visual Studio 2010

Resources
Contents:
Microsoft Learning

13

Technet and MSDN Content

14

Programming in Visual Basic with Microsoft Visual Studio 2010

15-13

Microsoft Learning
This section describes various Microsoft Learning programs and offerings.

Microsoft Skills Assessments


Describes the skills assessment options available through Microsoft

Microsoft Learning
Describes the training options available through Microsoft face-to-face or self-paced

Microsoft Certification Program


Details how to become a Microsoft Certified Professional, Microsoft Certified Database
Administrators, and more

Microsoft Learning Support

To provide comments or feedback about the course, send e-mail to support@mscourseware.com

To ask about the Microsoft Certification Program (MCP), send e-mail to mcphelp@microsoft.com

Programming in Visual Basic with Microsoft Visual Studio 2010

15-14

Technet and MSDN Content


This section includes content from TechNet for this course.

Try...Catch...Finally Statement (Visual Basic)

Exception Members

File Class

FileInfo Class

Directory Class

DirectoryInfo Class

Path Class

Development with My (Visual Basic)

ApplicationBase Class

Computer Class

User Class

FileStream Class

StreamWriter Class

StreamReader Class

BinaryWriter Class

BinaryReader Class

Enum Statement (Visual Basic)

Using Constructors and Destructors

Partial (Visual Basic)

Partial Methods (Visual Basic)

ByRef (Visual Basic)

Private (Visual Basic)

Public (Visual Basic)

Friends (Visual Basic)

Shared (Visual basic)

Extension Methods (Visual Basic)

Object Class

TryCast Operator (Visual Basic)

TypeOf Operator (Visual Basic)

Polymorphism

MustInherit (Visual Basic)

MustOverride (Visual Basic)

Programming in Visual Basic with Microsoft Visual Studio 2010

Property Procedures (Visual Basic)

How to: Declare and Call a Default Property in Visual Basic

Object.Equals Method (Object)

Property Procedures (Visual Basic)

How to: Declare and Call a Default Property in Visual Basic

Object.Equals Method (Object)

Microsoft .NET

Visual Basic

What's New in Visual Basic 2010

Assemblies in the Common Language Runtime

Assembly Versioning

SignTool.exe (Sign Tool)

.NET Framework Tools

Main Procedure in Visual Basic

Console Class

Introduction to WPF

Control Library

Events (WPF)

Documenting Your Code with XML (Visual Basic)

Recommended XML Tags for Documentation Comments (Visual Basic)

Sandcastle Help File Builder

Option Strict Statement

Early and Late Binding (Visual Basic)

Visual Basic Keywords

General Naming Conventions

Capitalization Conventions

Option Explicit Statement

Scope in Visual Basic

CType Function (Visual Basic)

Convert Class

Type Conversion Functions

ReadOnly (Visual Basic)

Const Statement (Visual Basic)

Operators (Visual Basic)

15-15

Programming in Visual Basic with Microsoft Visual Studio 2010

15-16

StringBuilder Class

Main Procedure in Visual Basic

Array Class

If Operator (Visual Basic)

While...End While Statement (Visual Basic)

Do...Loop Statement (Visual Basic)

For...Next Statement (Visual Basic)

Procedures in Visual Basic

Procedure Overloading (Visual Basic)

Parameter Arrays (Visual Basic)

Optional Arguments (Visual Basic)

Passing Arguments by Value and by Reference (Visual Basic)

Delegates (Visual Basic)

Asynchronous Programming Overview

Lambda Expressions (Visual Basic)

Events (Visual Basic)

WithEvents (Visual Basic)

Handles Clause (Visual Basic)

Walkthrough: Declaring and Raising Events (Visual Basic)

Walkthrough: Handling Events (Visual Basic)

How to: Run an Operation in the Background

Object Lifetime: How Objects Are Created and Destroyed (Visual Basic)

GC Class

How to: Implement the Dispose Finalize Pattern (Visual Basic)

Using Statement (Visual Basic)

Object and Collection Initializers Overview (Visual Basic)

Commonly Used Collection Types

Generic Types in Visual Basic (Visual Basic)

Type List (Visual Basic)

Creating Variant Generic Interfaces (C# and Visual Basic)

ICollection(Of T) Interface

IList(Of T) Interface

IDictionary(Of TKey, TValue) Interface

IEnumerable(Of T) Interface

Programming in Visual Basic with Microsoft Visual Studio 2010

IEnumerator(Of T) Interface

Language-Integrated Query (LINQ)

Introduction to LINQ in Visual Basic

Basic Query Operations (Visual Basic)

LINQ Query Samples - Query Execution

Expression Trees (C# and Visual Basic)

System.Linq.Expressions Namespace

Expression Class

How to: Use Expression Trees to Build Dynamic Queries (C# and Visual Basic)

Dynamic Language Runtime Overview

Working with Dynamic Objects (Visual Basic)

COM Data Types

Tlbimp.exe (Type Library Importer)

15-17

15-18

Programming in Visual Basic with Microsoft Visual Studio 2010

Send Us Your Feedback


You can search the Microsoft Knowledge Base for known issues at Microsoft Help and Support before
submitting feedback. Search using either the course number and revision, or the course title.
Note Not all training products will have a Knowledge Base article if that is the case, please
ask your instructor whether or not there are existing error log entries.

Courseware Feedback
Send all courseware feedback to support@mscourseware.com. We truly appreciate your time and effort.
We review every e-mail received and forward the information on to the appropriate team. Unfortunately,
because of volume, we are unable to provide a response but we may use your feedback to improve your
future experience with Microsoft Learning products.

Reporting Errors
When providing feedback, include the training product name and number in the subject line of your email. When you provide comments or report bugs, please include the following:
1.

Document or CD part number

2.

Page number or location

3.

Complete description of the error or suggested change

Please provide any details that are necessary to help us verify the issue.
Important All errors and suggestions are evaluated, but only those that are validated are
added to the product Knowledge Base article.