Professional Documents
Culture Documents
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.
1-1
Module 1
Introducing Visual Basic and the .NET Framework
Contents:
Lesson 1: Introduction to the .NET Framework 4
11
16
19
24
27
29
32
1-2
Lesson 1
Additional Reading
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.
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.
1-3
1-4
Additional Reading
What Is the .NET Framework 4?
For more information about the .NET Framework, see Microsoft .NET.
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).
1-5
Lesson 2
1-6
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.
A Web site that you will host on an Internet Information Services (IIS) Web server.
For a client application, you could use the WPF Application and Windows Forms Application
templates.
For a Web site, you could use the ASP.NET Web Application and ASP.NET MVC 2 Application
templates.
1-7
1-8
Right-click the Start menu, and then click Open Windows Explorer.
2.
3.
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.
Right-click the Start menu, and then click Open Windows Explorer.
2.
2.
In the Open dialog box, browse to the D:\Demofiles\Mod1\Demo1 folder, and then doubleclick MyFirstApplication.exe.
In the IL DASM window, in the output pane, point to the Manifest node and explain that this is
stored alongside the assembly.
2.
3.
In the Manifest window, show students the following, and then close the Manifest window:
4.
5.
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
application. Inform students that the concept of the Main method will be covered in the next
lesson.
8.
9.
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.
1-9
1-10
Lesson 3
Additional Reading
1-11
1-12
Additional Reading
Structure of a Console Application
For more information the Main procedure, see Main Procedure in Visual Basic.
1-13
Lesson 4
Additional Reading
1-14
For labels for the user name and password, use Label controls.
For input boxes for the user name and password, use TextBox controls.
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.
Solution Explorer
Properties
XAML
Design
Code Editor
Additional Reading
What Is Windows Presentation Foundation?
For more information about what WPF is, visit Introduction to WPF.
WPF Events
For more information about how WPF handles events, see Events (WPF).
1-15
1-16
On the Start menu, point to All Programs, click Microsoft Visual Studio 2010, and then click
Microsoft Visual Studio 2010.
2.
3.
In the New Project dialog box, perform the following tasks, and then click OK:
a)
b)
c)
2.
3.
Show students the control in the Design window, and the XAML markup in the XAML window.
2.
In the Properties window, on the Properties tab, set the following properties:
Name: ClickMeButton
FontSize: 20
Height: 50
Width: 150
3.
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
1-17
4.
Explain to students that you have just added code so that, when the button is clicked, a message
box is displayed.
2.
3.
In the MainWindow window, click Click Me, and then click OK.
4.
1-18
Lesson 5
Documenting an Application
Contents:
Question and Answers
Additional Reading
1-19
1-20
Additional Reading
What Are XML Comments?
For more information about XML comments, see Documenting Your Code with XML (Visual
Basic).
1-21
Lesson 6
1-22
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.
2.
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.
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.
1-23
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:
Declare variables by using meaningful names and avoid reference to the underlying data type,
such as nameString.
1-24
Define controls by using meaningful names and suffix using the underlying control type, such as
NameLabel.
1-25
Tools
Tool
Use to
Where to find it
Gacutil.exe
C:\Program Files
\Microsoft SDKs\Windows
\v7.0A\bin
Ildasm.exe
C:\Program Files
\Microsoft SDKs\Windows
\v7.0A\bin
Makecert.exe
C:\Program Files
\Microsoft SDKs\Windows
\v7.0A\bin
Ngen.exe
C:\Windows\Microsoft.NET
\Framework\v4.0.30319
Sn.exe
C:\Program Files
\Microsoft SDKs\Windows
\v7.0A\bin
1-26
2-1
Module 2
Introducing Visual Basic and the .NET Framework
Contents:
Lesson 1: Declaring Variables and Assigning Values
11
14
17
18
2-2
Lesson 1
Additional Reading
2-3
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
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).
2-5
Lesson 2
Additional Reading
2-6
Additional Reading
What Are Operators?
For more information about the operators in Visual Basic, see Operators (Visual Basic).
2-7
2-8
Lesson 3
9
10
Indexer
GetValue
Explicit GetEnumerator
Implicit GetEnumerator
2-9
2-10
Additional Reading
Creating and Initializing Arrays
For more information the Main procedure, see Main Procedure in Visual Basic.
2-11
Lesson 4
12
Additional Reading
13
2-12
Additional Reading
Using Either-Or If Statements
For more information about the If operator, see If Operator (Visual Basic).
2-13
2-14
Lesson 5
15
Additional Reading
16
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).
Instructions for how to modify the counter variable at the end of each iteration.
2-15
2-16
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).
2-17
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
3-1
Module 3
Declaring and Calling Methods
Contents:
Lesson 1: Defining and Invoking Methods
12
13
3-2
Lesson 1
Additional Reading
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")
The parameter array must be the last parameter in the parameter list.
3-3
3-4
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.
Additional Reading
Creating a Method
For more information about procedures or methods, see Procedures in Visual Basic.
3-5
3-6
Click Start, point to All Programs, click Microsoft Visual Studio 2010, and then click Microsoft
Visual Studio 2010.
1.
2.
In the Open Project dialog box, browse to the D:\Demofiles\Mod3\Demo1\Starter folder, and
then double-click MethodRefactorAndTestDemo.sln.
3.
4.
Explain that the Main method includes some code to generate an array of random numbers
based on the following three constraints:
5.
6.
7.
8.
Explain that you want to use this code elsewhere in your application, so you are going to refactor
it into a new method.
In the Code Editor window, in the Main method, select all the code.
2.
3.
Below the Main method, create a new Function named GenerateRandomNumbers, and paste
in the copied code.
Private
Dim
Dim
Dim
3-7
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
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.
2.
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.
3-8
2.
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.
3-9
Lesson 2
10
Additional Reading
11
3-10
Additional Reading
What Are Optional Parameters?
For more information about optional parameters, see Optional Arguments (Visual Basic).
3-11
3-12
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.
3-13
Module 4
Handling Exceptions
Contents:
Lesson 1: Handling Exceptions
10
4-1
4-2
Lesson 1
Handling Exceptions
Contents:
Question and Answers
Additional Reading
4-3
4-4
Additional Reading
Using a Try/Catch Block
For more information about Try/Catch blocks, see the Try...Catch...Finally Statement (Visual Basic) page.
4-5
Click Start, point to All Programs, click Microsoft Visual Studio 2010, and then click Microsoft
Visual Studio 2010.
2.
3.
4.
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.
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.
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.
Task 3: Modify the exception configuration in Visual Studio to always throw exceptions.
1.
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
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.
6.
For the System.NullReferenceException row, clear the User-unhandled check box, and
then select the Thrown check box.
7.
Lesson 2
Raising Exceptions
Contents:
Question and Answers
4-7
4-8
Throwing an Exception
Question: Where does execution continue after you perform a Throw statement?
Answer: The next Catch block in the call stack.
4-9
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 display detailed exception messages to the user because a malicious user could use detailed
technical information to make your application malfunction.
4-10
Module 5
Reading and Writing Files
Contents:
Lesson 1: Accessing the File System
10
5-1
5-2
Lesson 1
Additional Reading
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.
2.
5-3
5-4
3.
4.
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.
5-5
5-6
Lesson 2
Additional Reading
The ability to read and write large amounts of data without consuming resources
such as memory and network bandwidth.
5-7
5-8
Additional Reading
What are Streams?
For more information about the FileStream class, see the FileStream Class page.
5-9
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
Module 6
Creating New Types
Contents:
Lesson 1: Creating and Using Modules and Enumerations
14
15
6-1
6-2
Lesson 1
Additional Reading
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.
6-3
6-4
Additional Reading
Creating New Enum Types
For more information about enumerations, see the Enum Statement (Visual Basic) page.
Lesson 2
Additional Reading
6-5
6-6
Creating Objects
Question: Which operator must you use when you initialize a class to create an instance of
that class?
Answer: The New operator.
6-7
Additional Reading
Defining Constructors and Initializing an Object
For more information about constructors, see the Using Constructors and Destructors page.
6-8
Lesson 3
Answer: Yes. It is legal because the Integer type is an alias for the System.Int32 type.
6-9
6-10
Lesson 4
11
Additional Reading
13
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.
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.
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
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
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
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.
6-15
Module 7
Encapsulating Data and Methods
Contents:
Lesson 1: Controlling Visibility of type Members
10
7-1
7-2
Lesson 1
Additional Reading
Answer: The constructor is private, so you cannot instantiate a Product object to use any of
its public instance members.
7-3
7-4
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.
Lesson 2
Additional Reading
7-5
7-6
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
Additional Reading
Creating and Using Shared Methods
For more information about the static modifier, see the Shared (Visual basic) page.
7-9
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
Module 8
Inheriting from Classes and Implementing Interfaces
Contents:
Lesson 1: Using Inheritance to Define New Reference Types
11
17
18
8-1
8-2
Lesson 1
Additional Reading
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.
8-3
8-4
Additional Reading
.NET Framework Inheritance Hierarchy
For more information about the Object class, see the Object Class page.
Understanding Polymorphism
For more information about polymorphism, see the Polymorphism page.
8-5
2.
3.
Click Start, point to All Programs, click Microsoft Visual Studio 2010, and then click
Microsoft Visual Studio 2010.
b.
In Solution Explorer, double-click Module1.vb. Add the following code to the file:
Class Television
End Class
4.
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
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.
Lesson 2
8-7
8-8
8-9
2.
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
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.
Lesson 3
12
Additional Reading
13
14
8-11
8-12
Additional Reading
What is an Abstract Class?
For more information about the MustInherit modifier, see the MustInherit (Visual Basic) page.
8-13
8-14
2.
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
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
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
8-17
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.
Use interfaces wherever possible as a contract that specifies what methods a class will expose.
Use abstract classes to abstract common functionality and reduce code duplication.
8-18
9-1
Module 9
Managing the Lifetime of Objects and Controlling Resources
Contents:
Lesson 1: Introduction to Garbage Collection
11
12
9-2
Lesson 1
Additional Reading
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.
9-3
9-4
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.
9-5
2.
3.
Click Start, point to All Programs, click Microsoft Visual Studio 2010, and then
click Microsoft Visual Studio 2010.
b.
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.
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.
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.
9.
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.
9-6
Lesson 2
Managing Resources
Contents:
Question and Answers
Additional Reading
9-7
9-8
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.
9-9
2.
3.
Click Start, point to All Programs, click Microsoft Visual Studio 2010, and then
click Microsoft Visual Studio 2010.
b.
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
4.
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.
Press Ctrl+F5.
7.
8.
Point out the unhandled exception. Explain that the Using statement prevented these
exceptions.
9-11
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
Module 10
Encapsulating Data and Defining Overloaded Operators
Contents:
Lesson 1: Creating and Using Properties
12
17
18
10-1
10-2
Lesson 1
Additional Reading
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.
10-3
10-4
Additional Reading
What Is a Property?
For more information about properties, see the Property Procedures (Visual Basic) page.
10-5
10-6
2.
3.
b.
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.
5.
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.
10-7
Console.ReadLine()
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.
Explain that the code attempts to set James salary to a negative value. Remind
students that the property prevented negative values.
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.
10-8
Lesson 2
Additional Reading
10
11
10-9
10-10
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.
10-11
2.
3.
Click Start, point to All Programs, click Microsoft Visual Studio 2010, and then
click Microsoft Visual Studio 2010.
b.
Open the EmployeeDatabase.vb file, and then review the EmployeeDatabase class:
a.
b.
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.
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.
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.
10-12
Lesson 3
Overloading Operators
Contents:
Question and Answers
13
Additional Reading
14
15
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.
10-13
10-14
Additional Reading
Restrictions When Overloading Operators
For more information about using the Equals method, see the Object.Equals Method (Object) page.
10-15
2.
3.
Click Start, point to All Programs, click Microsoft Visual Studio 2010, and then
click Microsoft Visual Studio 2010.
b.
Open the EmployeeDatabase.vb file, and then review the EmployeeDatabase class:
a.
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.
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.
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.
10-16
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.
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.
10-17
11-1
Module 11
Decoupling Methods and Handling Events
Contents:
Lesson 1: Declaring and Using Delegates
13
15
11-2
Lesson 1
Additional Reading
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
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.
11-5
Lesson 2
Additional Reading
11-6
Additional Reading
Defining Lambda Expressions
For more information about lambda expressions, see Lambda Expressions (Visual Basic).
11-7
11-8
Lesson 3
Handling Events
Contents:
Question and Answers
Additional Reading
10
11
11-9
11-10
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).
11-11
2.
3.
Click Start, point to All Programs, click Microsoft Visual Studio 2010, and then
click Microsoft Visual Studio 2010.
b.
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.
b.
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.
11-12
11-13
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.
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.
11-14
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:
11-15
Module 12
Using Collections and Building Generic Types
Contents:
Lesson 1: Using Collections
11
14
18
19
12-1
12-2
Lesson 1
Using Collections
Contents:
Question and Answers
12-3
Additional Reading
12-4
12-5
12-3
12-4
Additional Reading
Using Collection Classes
For more information about collection initializers, see the Object and Collection Initializers Overview
(Visual Basic) page.
12-5
2.
3.
Click Start, point to All Programs, click Microsoft Visual Studio 2010, and then click
Microsoft Visual Studio 2010.
b.
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.
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:
12-6
Lesson 2
12-7
Additional Reading
12-8
12-9
12-7
12-8
Additional Reading
What Are Generic Types?
For more information about generics, see the Generic Types in Visual Basic (Visual Basic) page.
12-9
2.
3.
Click Start, point to All Programs, click Microsoft Visual Studio 2010, and then click
Microsoft Visual Studio 2010.
b.
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.
12-10
Lesson 3
12-12
Additional Reading
12-13
12-11
12-12
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.
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
Lesson 4
12-15
12-16
12-15
12-16
2.
3.
Click Start, point to All Programs, click Microsoft Visual Studio 2010, and then click
Microsoft Visual Studio 2010.
b.
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.
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.
Press Ctrl+F5.
12-17
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:
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.
12-18
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.
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.
Use constraints on generic types to provide control over types that are used with your generic classes.
Use the Action and Func generic delegates, instead of custom delegates, wherever possible.
12-19
Module 13
Building and Enumerating Custom Collection Classes
Contents:
Lesson 1: Implementing a Custom Collection Class
10
11
13-1
13-2
Lesson 1
13-3
Additional Reading
13-5
13-3
13-4
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.
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
Lesson 2
13-7
Additional Reading
13-9
13-7
13-8
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.
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.
13-10
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.
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.
13-11
Module 14
Using LINQ to Query Data
Contents:
Lesson 1: Using the LINQ Extension Methods and Query Operators
10
11
14-1
14-2
Lesson 1
14-3
Additional Reading
14-5
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
=
=
=
=
=
=
=
Ordering Data
Question: Which extension method would you use to sort an array of strings into
descending order?
Answer: The OrderByDescending extension method.
IEnumerable(Of Customer) =
With
With
With
With
With
With
With
{.FirstName
{.FirstName
{.FirstName
{.FirstName
{.FirstName
{.FirstName
{.FirstName
=
=
=
=
=
=
=
14-3
14-4
Dim result =
customers.Count(Function(cust) cust.LastName.StartsWith("P"))
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.
Answer: Yes, both code examples produce the same result of 232.12.
14-5
Additional Reading
What Is the Purpose of LINQ?
For more information about LINQ, see the Language-Integrated Query (LINQ) page.
14-6
Lesson 2
14-7
Additional Reading
14-9
14-7
/
/
/
>
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.
14-8
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.
14-9
14-10
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.
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.
14-11
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
10
11
15-2
Lesson 1
Additional Reading
15-3
15-4
Additional Reading
What Is the Dynamic Language Runtime?
For more information about the DLR, see the Dynamic Language Runtime Overview page.
15-5
1.
b.
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.
2.
3.
4.
5.
Click Start, point to All Programs, click Microsoft Visual Studio 2010, and then click
Microsoft Visual Studio 2010.
b.
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 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
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.
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.
b.
Press Ctrl+F5.
c.
Telephone: 888
Telephone: 999
Lesson 2
Additional Reading
15-7
15-8
Additional Reading
Interoperating with COM from a Visual Basic Application
For more information about marshaling COM data types, see the COM Data Types page.
15-9
15-10
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.
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.
15-11
15-12
Resources
Contents:
Microsoft Learning
13
14
15-13
Microsoft Learning
This section describes various Microsoft Learning programs and offerings.
Microsoft Learning
Describes the training options available through Microsoft face-to-face or self-paced
To ask about the Microsoft Certification Program (MCP), send e-mail to mcphelp@microsoft.com
15-14
Exception Members
File Class
FileInfo Class
Directory Class
DirectoryInfo Class
Path Class
ApplicationBase Class
Computer Class
User Class
FileStream Class
StreamWriter Class
StreamReader Class
BinaryWriter Class
BinaryReader Class
Object Class
Polymorphism
Microsoft .NET
Visual Basic
Assembly Versioning
Console Class
Introduction to WPF
Control Library
Events (WPF)
Capitalization Conventions
Convert Class
15-15
15-16
StringBuilder Class
Array Class
Object Lifetime: How Objects Are Created and Destroyed (Visual Basic)
GC Class
ICollection(Of T) Interface
IList(Of T) Interface
IEnumerable(Of T) Interface
IEnumerator(Of T) Interface
System.Linq.Expressions Namespace
Expression Class
How to: Use Expression Trees to Build Dynamic Queries (C# and Visual Basic)
15-17
15-18
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.
2.
3.
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.