Sie sind auf Seite 1von 173

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

6367A
Introduction to Object-Oriented Programming with Microsoft Visual Studio 2008 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. 2010 Microsoft Corporation. All rights reserved. Microsoft and the trademarks listed at http://www.microsoft.com/about/legal/en/us/IntellectualProperty/Trademarks/EN-US.aspx are trademarks of the Microsoft group of companies. All other marks are property oftheir respective owners.

Product Number: 6367A Released: 01/2010

Getting Started with Object-Oriented Programming

1-1

Module 1
Getting Started with Object-Oriented Programming
Contents:
Lesson 1: Introduction to Object-Oriented Programming Lesson 2: Creating Projects in Visual Studio 2008 Lesson 3: Coding in Visual Studio 2008 Lesson 4: Productivity Features in Visual Studio 2008 Lesson 5: Debugging Visual Studio Applications Module Reviews and Takeaways Lab Review Questions and Answers 2 6 11 14 19 23 25

1-2

Introduction to Object-Oriented Programming with Microsoft Visual Studio 2008

Lesson 1

Introduction to Object-Oriented Programming


Contents:
Question and Answers Additional Reading 3 4

Getting Started with Object-Oriented Programming

1-3

Question and Answers


Object-Oriented Application Design Goals
Question: What are the goals behind producing optimal software? Answer: Answers will vary, but may include maximizing code reuse, simplifying code maintenance, and reducing time required to release new code versions. Question: How have you addressed reducing maintenance for the code you have written? Answer: Answers will vary based on experience, but may include creating reusable modules, keeping code loosely coupled, and avoiding hard coding of values. Question: What kind of difficulties have you experienced while maintaining someone elses code? Answer: Answers will vary based on experience, but may include a lack of documentation, code complexity, hard-coded values, and tightly-coupled code.

Procedural vs. Object-Oriented Programming


Question: Have you ever been involved in developing or designing an object-oriented application? What was your experience? Answer: Answers will vary based on experience. Question: Have you worked on code that was difficult to maintain? What made it difficult? Answer: Answers will vary based on experience, but may include lack of documentation, code complexity, hard-coded values, and tightly-coupled code.

Development Success Factors


Question: What are some of the external influencing factors that affect your development? Answer: Answers will vary based on experience, but may include deadlines, budgets, software licenses, existing contracts, and development team skills.

Support for Object-Oriented Development in .NET and Visual Studio 2008


Question: How can you use these features at work to speed up design, development, or testing? Answer: Answers will vary, but may include using Object Test Bench to test methods and classes, and using class view and object browser to determine contents of existing classes. Question: Have you used other tools during object-oriented development? Answer: Answers will vary based on experience, but may include modeling tools, code generation tools, automated testing tools, or Microsoft Visual Studio Team System 2008, which helps with the entire project life cycle.

1-4

Introduction to Object-Oriented Programming with Microsoft Visual Studio 2008

Additional Reading
Support for Object-Oriented Development in .NET and Visual Studio 2008
Visual Studio 2005 Class Designer Object Browser Object Test Bench Drill Into .NET Framework Internals to See How the CLR Creates Runtime Objects

Getting Started with Object-Oriented Programming

1-5

Lesson 2

Creating Projects in Visual Studio 2008


Contents:
Question and Answers Detailed Demo Steps Additional Reading 6 7 9

1-6

Introduction to Object-Oriented Programming with Microsoft Visual Studio 2008

Question and Answers


Visual Studio 2008 Projects
Question: What types of applications will you use at work? Which project types are best suited for those applications? Answer: Answers will vary, but may include building internal applications using Windows Applications, building external Web sites using Microsoft ASP.NET Web Applications, writing applications that can be accessed by external applications using ASP.NET Web services, or creating shared classes to be used by .NET applications using Class libraries.

Visual Studio Solution/Project Structure


Question: When would you create multiple projects within a solution? Answer: Answers will vary, but creating multiple projects in a solution can break an application into units of work that can be divided among programmers. Different types of projects can be added to a solutionsuch as test projects and deployment projectsto help test or deploy a project.

Visual Studio Project Types


Question: Why would you consider a Windows Application over a Web Application? Answer: The Windows application provides a richer graphical interface and more client processing power than the Web applications. Imagine using a Web application to perform photo editingthe data that would need move across the network would be prohibitively large. Question: What project types will you use at work? Answer: Answers will vary, and may include any of the project types listed.

Creating Projects in Visual Studio 2008


Question: What is type of container should you use to organize multiple related development projects in Visual Studio 2008? Answer: You should use a solution container. Question: What type of project should you create that can contain multiple code classes that can be used by other applications such as .exes, console applications, and Web applications? Answer: You should create a class library.

Getting Started with Object-Oriented Programming

1-7

Detailed Demo Steps


Demonstration: Creating Projects in Visual Studio 2008 Detailed demonstration steps
1. 2. 3. Start Visual Studio 2008. On the Start page, under Recent Projects, next to the Create label, click Project. Depending on the language you wish to select: a. or b. 4. 5. For Visual C#, expand Other Languages, expand Visual C#, click Web as the project type, and then select ASP.NET Web Application as the template. For Visual Basic, expand Visual Basic, click Web as the project type, and then select ASP.NET Web Application as the template.

Modify the properties as required, and then click OK. A new project will be created for you. Take note of the following features: a. b. c. There is a menu structure at the top of the application (File, Edit, View ), and a toolbar directly below. In the center of the page is the design canvas where you design the application interface. In our case, this is a Web form named Default.aspx. Left of the form is the toolbox. Click the toolbox so that it expands, and notice the variety of controls. These are controls for a Web form, and that the controls for a windows form are different. In the top, right corner, highlight the solution explorer. The tree-view makes it easy to access all solution components. Note the following files that are created by this project template: i. ii. iii. Default.aspx: The first Web form of the application. Expand the tree and note the codebehind files (.cs or .vb files). config file: The .xml file for storing Web site configuration settings. Lastly, note the Properties window on the bottom, right corner. The currently selected objects properties are displayed in the window.

d.

6.

You currently have a solution with a single project. In most real world solutions the solution consists of multiple projects. To add a Web site to the solution, click File, click Add, and then click New Web Site. On the dialog box ensure ASP.NET Web Site is selected. Keep the other default settings, but select the language of your choice and then click OK. A new Web site adds to the solution. Note that a Web site is a simple ad-hoc Web site, whereas a Web application has all the makings of a Visual Studio 2008 project. You can demonstrate this by showing the properties differences of the last two projects. a. b. Right-click the Web site project, and then click property pages. Take note of the items available, and then close the window. Right-click on the Web application, and then select properties. Click the tabs, and take note of the large number of settings that are available. Close the Properties window.

7.

1-8

Introduction to Object-Oriented Programming with Microsoft Visual Studio 2008

8.

Add a class library project to the solution. Click File, click Add, and then click New Project. Under Project Types, select the language of your choice, and then click Windows. Select Class Library as the template. Change the name to ClassLibraryDemo, and then click OK. A new class library adds to the solution, and class1 should open in the code view.

9.

10. To add a Windows Forms Application, click File, click Add, and then click New Project. Under Project Types, select the language of your choice, and then click Windows. Select Windows Forms Application as the template. Change the name to WindowsFormsDemo, and then click OK. 11. A new Windows Forms application will be added to the solution, and form1 will display in the designer. Review the files that have been created for this project. 12. Right-click Class1 in the ClassLibraryDemo project, and select View Code. In Class1, write a method that will take a string as input and return it in the uppercase. 13. Right-click the WindowsFormsDemo and select Add Reference. Click the Projects tab, click ClassLibraryDemo and then click OK. Switch to Form1 in designer mode, and then drag and drop a button and textbox control onto the form. Change the text property of the button to Click Me. Double-click on the button, and add code that will instantiate an instance of the ClassLibraryDemo. Call the ChangeToUpper method with the contents of the text box, and then display the result in a messagebox. 14. Right-click the WindowsFormsDemo, and then click Set as startup project. 15. On the menu bar, click Build, and then click Build Solution. Ensure that the build succeeds, Notice the status is in the bottom left of the window. 16. Press the F5 key to start executing the project. 17. When the form loads, type hello world into the text box, and then click the Click Me button. The text HELLO WORLD should display in the message box. Stop executing the application. 18. Optional: If you have time, you can repeat a similar exercise with the Web application. 19. Leave the current solution open for the next demonstration.

Getting Started with Object-Oriented Programming

1-9

Additional Reading
Visual Studio Project Types
Default Project Templates in Visual Studio

Web Projects
Web Application Projects Overview Comparing Web Site Projects and Web Application Projects

1-10

Introduction to Object-Oriented Programming with Microsoft Visual Studio 2008

Lesson 3

Coding in Visual Studio 2008


Contents:
Question and Answers Additional Reading 11 12

Getting Started with Object-Oriented Programming

1-11

Question and Answers


Reference Types
Question: Why is it important to know whether a type is value or reference? Answer: value and reference types are handled differently in memory. It is important to know how memory is allocated and released in an application.

Defining Collections
Question: What is the benefit of using a generic collection? Answer: A generic collection can store any type, but you specify the type to store when you instantiate the collection. This makes the collection type-safe.

Controlling Flow
Question: When should you use an IF statement instead of a SELECT/SWITCH? Answer: Use an IF statement if multiple variables and factors will determine what code to execute. A SELECT/SWITCH statement can only examine a single variable to determine the appropriate path to follow.

Type Conversion
Question: Why should you explicitly convert your data types? Answer: If you rely on .NET to convert your data types, you may have unexpected results because.NET may not convert types the way you expect. For example, if you try to add two string variables that contain integers, .NET will concatenate the strings when you may want the two strings to be converted to integers and then added together.

Generic Types
Question: What is the value of using a generic collection? Answer: Generic collections provide type safety so you control the types that can be stored in the collection at runtime.

1-12

Introduction to Object-Oriented Programming with Microsoft Visual Studio 2008

Additional Reading
Value Types
Value Types in the Common Type System .NET Type Fundamentals

Reference Types
.NET Type Fundamentals

Defining Collections
System.Collections.Generic Namespace

Type Conversion
IConvertible Interface Casting and Type Conversions (C# Programming Guide) How to: Convert a string to an int (C# Programming Guide) Converting Types

Getting Started with Object-Oriented Programming

1-13

Lesson 4

Productivity Features in Visual Studio 2008


Contents:
Question and Answers Detailed Demo Steps Additional Reading 14 15 17

1-14

Introduction to Object-Oriented Programming with Microsoft Visual Studio 2008

Question and Answers


Coding Productivity Features in Visual Studio 2008
Question: What is the benefit to using XML documentation instead of simply documenting your code in a separate document such as an Office Word document? Answer: Anyone maintaining the application will always have access to the documentation. Even if the original XML document is lost, it can easily be regenerated from the application code. Question: Are there situations where you were coding and would have benefited from code refactoring? Answer: Answers will vary based on experience.

Demonstration: Using Productivity Features


Question: What is the shortcut key (in Visual Basic and Visual C#) for adding a comment block for a procedure or function? Answer: In Visual C# the shortcut key is /// and in Visual Basic the shortcut key is .

Commenting and Documenting Code


Question: Why is it important to document your code? Answer: When you are working with the code every day, the code logic may seem obvious. However, to someone who is looking at code for the first time, or the for the first time after many months, it is important to explain the purpose of variables, methods, and classes, so that the code can be easily understood an maintained.

Getting Started with Object-Oriented Programming

1-15

Detailed Demo Steps


Demonstration: Using Productivity Features Detailed demonstration steps
Adding comments to code
1. 2. Ensure you have the solution used in the previous demonstration open. Right-click class1 in the ClassLibraryDemo, and then click View Code. In the code editor window, just above the public function ChangeToUpper, complete one of the following steps: a. b. 3. If using Visual Basic, type in three apostrophes . If using Visual C#, type in three forward slashes ///.

An XML code snippet will be inserted to create a template for comments. In the summary element, type This function receives a string as input and then returns it in the uppercase. Within the ChangeToUpper function, add a comment by completing one of the following steps: a. b. If using Visual Basic, add the following line: This line returns the value. If using Visual C# add the following line: //This line returns the value.

4.

Generating documentation from code comments


1. Right-click the ClassLibraryDemo project, and then select Properties. a. b. If using Visual C#, select the Build tab, select the XML Documentation file check box, and then verify that ClassLibraryDemo.xml is specified in the text box. If using Visual Basic, select the Compile tab, and then select the Generate XML documentation file. There is no need to provide a file name as it will be the same as that of the assembly.

2.

Build the project. Navigate to the bin\debug\ folder, and then open the ClassLibraryDemo.xml file. Highlight the comments that have been placed in the XML file.

Note: the normal inline comments are not added, only the summary comments.

3.

Close the project window and the ClassLibraryDemo.xml file

Using code snippets


1. Return to the ChangeToUpper function, and complete one of the following steps: a. If using Visual Basic: Above the line the returns the value, right-click and select Insert Snippet. From the context menu, select Code Patterns, select Conditionals and loops. Finally, double-click the If..Else..End If statement. You should notice a code snippet being

1-16

Introduction to Object-Oriented Programming with Microsoft Visual Studio 2008

inserted into the function. Edit the code snippet so that your function looks like the following:

Public Function ChangeToUpper(ByVal input As String) As String If input.Length > 0 Then This line returns the value Return input.ToUpper() Else Return End If End Function

b. c.

If using Visual C#: Above the line that returns the value, right-click and select Insert Snippet, double click Visual C#, double click and select if (not #if), and then double click. You should notice a code snippet being inserted into the function. Edit the code snippet so that your function looks like this:

public string ChangeToUpper(string input) { if (input.Length > 0) { //This line returns the value return input.ToUpper(); } else { return ; } }

Refactoring code
1. Return to the ChangeToUpper function, and rename the functions input parameter to inputstring. You will notice a red underscore under the renamed variable which is different than the red underlines under the broken references to the variable. Mouse over the red underscore at the end of inputstring and then over the refactoring icon that appears. Click the down arrow, and then select Rename input to inputstring. The input variable in the code block will be renamed to inputstring. If Refactoring Warning dialog box appears, click Continue. Leave the solution open for the next demonstration.

2. 3.

Getting Started with Object-Oriented Programming

1-17

Additional Reading
Coding Productivity Features in Visual Studio 2008
XML Documentation Comments (C# Programming Guide) Whats new in Visual Studio 2008 Using IntelliSense

Commenting and Documenting Code



XML Comments Let You Build Documentation Directly From Your Visual Studio .NET Source Files Documenting Your Code with XML (Visual Basic)

1-18

Introduction to Object-Oriented Programming with Microsoft Visual Studio 2008

Lesson 5

Debugging Visual Studio Applications


Contents:
Question and Answers Detailed Demo Steps 19 20

Getting Started with Object-Oriented Programming

1-19

Question and Answers


Debugging Interface Features
Question: What is the difference between Step Into and Step Over? Answer: Step Into will step into the code of the method called, while Step Over will execute the method called, and continue to the next line of code in the calling code.

Demonstration: Using the Debugging Interface


Question: Can you create a condition on a breakpoint? Answer: Yes you can, for example a hit counter.

Test Projects
Question: What is the benefit of creating a test project? Answer: Taking the time to create a test project when you first do testing will save time later, because you will be able to quickly retest any code changes by re-executing the existing tests.

1-20

Introduction to Object-Oriented Programming with Microsoft Visual Studio 2008

Detailed Demo Steps


Demonstration: Using the Debugging Interface Detailed demonstration steps
Adding breakpoints
1. 2. Ensure that you have the solution used in the previous demonstration open. Right-click Form1 in the WindowsFormsDemo project, and then click ViewCode. Navigate to the Button1_Click function. In the line that calls the MessageBox function, click in the margin to add a breakpoint to the code. Right-click the WindowsFormsDemo project and select Set as Startup project.

3.

Place an application in debug mode and stepping through code


1. Press F5 to start debugging. The application will start up and load the window. Type hello world into the text box, and then click Click Me. Once the breakpoint is hit, the application will break into debug mode. Click the Debug menu. Notice the difference between Step Into, Step Over, and Step Out. You can also continue executing the code by pressing F5 again.

2.

Viewing and editing variables


1. Place the cursor over TextBox1.Text. You should see a tooltip that displays the current value of the text box text property. Demonstrate that you can change the current value of the variable by clicking between the quotes ()editing the text to hello new world, and then pressing Enter. Step into the method call, and select F8 or F11 depending on the configuration of Visual Studio 2008. Step into the ChangeToUpper method. Right-click the inputstring variable and select Quick Watch. When the Quick Watch window opens, review the information that can be seen. Close the window. Right-click the inputstring variable and select Add Watch. Watch the value in the window at the bottom of the screen. Select the Immediate Window tab, in the window type ?inputstring, and then press Enter. You will see the value of the variable displayed in the window. Continue stepping through the function code. Return to the calling procedure and wait for the messagebox to be displayed with the new value. When the messagebox displays, click OK and then press F5 to continue the code execution.

2. 3. 4. 5.

Editing and deleting breakpoints


1. Stop the application execution and return to the code with the breakpoint. Right-click the breakpoint in the margin, and discuss deleting and disabling a breakpoint. It is possible to set additional conditions on a breakpoint, such as a het counter. Remove a breakpoint by clicking on it. Leave the solution open for the next demonstraton instead of saving and closing it.

2. 3.

Getting Started with Object-Oriented Programming

1-21

Detailed Demo Steps


Demonstration: Creating a Test Project Detailed demonstration steps
Adding code comments
1. 2. 3. Ensure you have the solution used in the previous demonstration open Right-click the Class1 class in the ClassLibraryDemo project, and then select View Code. Place the cursor in the ChangeToUpper function, and then right-click and select Create Unit Test. When the Create Unit Test window is opened, ensure that the ChangeToUpper method is selected. Ensure the output project is set to a new test project of the language that you are using, and then click OK. When prompted for a name for the project, enter TestProjectDemo, and then click Create. (If you are using Visual C#, you may be prompted to add InternalsVisibleTo Attribute. Click Yes.) When the test project opens, navigate down ChangeToUpperTest method. Modify the code as follows:

4.

5.

[Visual C#]
[TestMethod()] public void ChangeToUpperTest() { Class1 target = new Class1(); string inputstring = Hello World; string expected = HELLO WORLD; string actual; actual = target.ChangeToUpper(inputstring); Assert.AreEqual(expected, actual);

[Visual Basic]
<TestMethod()> _ Public Sub ChangeToUpperTest() Dim target As Class1 = New Class1 Dim inputstring As String = Hello World Dim expected As String = HELLO WORLD Dim actual As String actual = target.ChangeToUpper(inputstring) Assert.AreEqual(expected, actual) End SubEnd Sub

6. 7.

Place a breakpoint on the first line of the test method. Place the cursor in the test method. From the menu bar, click Test, click Debug, and then click Tests in current context. The code will start executing and break into debug mode when it reaches the break point. Step through the code and into the target.ChangeToUpper method. Place the cursor over the inputstring input parameter, and view the current valued. Step through the rest of the code in the method. When you return to the test method, right-click the actual variable and select Quick Watch. Review the values in the window, and then close it.

8.

1-22

Introduction to Object-Oriented Programming with Microsoft Visual Studio 2008

9.

Continue stepping through the code. The test should pass. You should see the test as passed in the test results window at the bottom of the screen.

10. Change the expected string value to Hello world (H is uppercase). Rerun the test. This time the result should be a fail. 11. Save and close the project.

Getting Started with Object-Oriented Programming

1-23

Module Reviews and Takeaways


Review questions
1. What are the benefits of taking the time to design a fully object-oriented application? Answers will vary, but taking the time to design a solution up front will usually result in a more reusable, understandable, and maintainable application. 2. List the different project templates in Visual Studio 2008, and describe their purpose. 3. Windows Forms application used for building Windows applications Class Library used for sharing classes across applications ASP.NET Web Application for building Web sites ASP.NET Web Service Application for building Web services Console Application for building applications that are executed from the command line.

What features are offered in Visual Studio 2008 to help you create, maintain, and document your code? Answers will vary, but may include: XML documentation, unit testing, and code snippets.

Common issues related to object-oriented programming


Identify the causes for the following common issues related to Visual Studio 2008 features, and fill in the troubleshooting tips. For answers, refer to relevant lessons in the module. Issue XML comments have been used to document the code, but when the developer builds the code, the documentation does not appear. A test project has been added to the code, and values specified for the parameters and return value. Yet every time the test is executed, the test appears as inconclusive, even though the actual results match the expected results. Troubleshooting tip

The /doc option was not specified when compiling the project, or the Generate XML Documentation property was not set in the project properties.

The Assert.Inconclusive(Verify the correctness of this test method.) was not removed from the generated unit test code.

Real-world issues and scenarios


1. You have created a method and realize after starting to write the code that a variable you created should have been a parameter. What is the quickest way to resolve this problem? Use the refactor to promote the variable to a parameter. 2. You joined a new project team that is developing an application using Visual Studio 2008. There is no class diagram. You want to get an understanding of the existing classes and how they interact. How can you learn the existing classes and their relationships? Add a class diagram to the project and drag the existing classes to the class diagram to see the class architecture.

1-24

Introduction to Object-Oriented Programming with Microsoft Visual Studio 2008

3.

You have finished writing and testing the code for a class. Your code is sent back by the testing team because they have identified a bug. What feature should you use to speed up retesting your code after making the fix? Add a test project with methods to test your code.

Best practices related to developing an object-oriented application with Visual Studio 2008
Supplement or modify the following best practices for your own work situations: Use Test projects to unit test your code, so you can quickly retest all of your code whenever you make any modifications. Document your code within the project using comments or the XML documentation feature, so that anyone who has to maintain your code has access to documentation explaining the code. Take the time at the beginning of the project to think about object-oriented design, to create an elegant re-usable application that is easier to maintain. Set Option Strict=On for Visual Basic applications to ensure you do not implicitly convert one data type to another and lose data through narrowing.

Tools
Tool Class Designer Class View Object Browser Use for Documenting your class design and generating Code Browse the classes within your project Browse all the namespaces available to your project Where to find it

Visual Studio 2008 Visual Studio 2008 Visual Studio 2008

Getting Started with Object-Oriented Programming

1-25

Lab Review Questions and Answers


1. What is the difference between a solution and a project? Answer: A project is a collection of files (code, configuration, and resources) that maps to an assembly. A solution is a method of organizing multiple projects that together form a solution. 2. What is the shortcut key for adding a comment snippet? Answer: 3. In Visual Basic, the shortcut key is three apostrophes () In Visual C# the shortcut key is three forward slashes (///)

Can you name three methods to view the value of a variable while debugging? Answer: While in debug mode you can: a. b. c. Place the cursor over the variable Create a watch or quick watch Use the immediate window to query the variable

4.

Is it possible to set conditions on a break point? Answer: Yes it is. For example, when a specific value changes, or when a certain line of code is hit a certain number of times.

Implementing Classes, Properties and Methods

2-1

Module 2
Implementing Classes, Properties and Methods
Contents:
Lesson 1: Creating Classes Lesson 2: Implementing Properties within a Class Lesson 3: Implementing Methods within a Class Lesson 4: Using Class Properties and Methods Module Reviews and Takeaways Lab Review Questions and Answers 2 6 9 13 16 18

2-2

Introduction to Object-Oriented Programming with Microsoft Visual Studio 2008

Lesson 1

Creating Classes
Contents:
Question and Answers Additional Reading 3 5

Implementing Classes, Properties and Methods

2-3

Question and Answers


Introduction to Classes
Question: What other classes might you create for a banking application? Answer: Answers will vary. However, suggestions might include Customer, Branch, or Employee. Question: How would you handle ATM cards? Answer: ATM Card will probably be a class since it has a specific set of responsibilities: remembers a PIN number, remembers what accounts can be accessed, and has a unique card number.

Class Lifecycle
Question: What is the difference between allocation and instantiation? Answer: Allocation allocates the memory for the class, whereas instantiation initializes the class by running the constructor method of the class.

Class Constructors and Destructors


Question: Can you think of a situation where you would add a constructor to your class? Answer: Answers will vary. One example is adding a constructor for a Customer class. You could have a constructor that accepts the CustomerID. When the constructor executes, the class returns with a fully-populated customer class. Question: When might you have multiple constructor methods in your class? Answer: Answers will vary, but you should always have a constructor that accepts no parameters. Next you should consider what properties someone instantiating a class typically has to populate immediately after they create the class. Create a constructor that accepts these properties as parameters. Question: When might you have a destructor method in your class? Answer: You might have a destructor method when you have to release objects such as file handles, which use unmanaged resources.

Namespaces
Question: How do you access a class that is in a namespace from your client code? Answer: Either specify the fully qualified name of the class, or import the namespace with the statement Imports (Visual Basic) or using (Visual C#). Question: Why would two classes be in the same namespace?

2-4

Introduction to Object-Oriented Programming with Microsoft Visual Studio 2008

Answer: When two classes share something in common, they can share the same namespace.. A Savings Account class and a Checking Account class are both classes that are used to manage bank accounts.

Implementing Classes, Properties and Methods

2-5

Additional Reading
Introduction to Classes

Structures and Classes

Class Lifecycle

Garbage Collection: Automatic Memory Management in the Microsoft .NET Framework Garbage Collection

Class Attributes

Extending Metadata Using Attributes

2-6

Introduction to Object-Oriented Programming with Microsoft Visual Studio 2008

Lesson 2

Implementing Properties within a Class


Contents:
Question and Answers Additional Reading 7 8

Implementing Classes, Properties and Methods

2-7

Question and Answers


Defining Class Properties
Question: Why is it best practice to access fields through a property instead of accessing them directly? Answer: You can add code in a property method to perform validation and restrict the values that can be stored in the field. Question: What would be an example of a property for a BankAccount class? Answer: Answers will vary, but could include account number, account balance, and withdrawal limit.

Controlling Access to Properties


Question: Can you think of a situation where you might have a write-only property? Answer: Answers will vary depending on student experience. An example of a write-only property is Password, because you allow users to update their password but not retrieve it. Question: Can you think of an example where you might have a read-only property? Answer: Answers will vary. Age is a good example. You might have a property for date of birth, and age would be a read-only property that is calculated based on date of birth.

Reference Type Properties


Question: What is the advantage to returning an object? Answer: Passing types allows for references to be passed. This is more efficient, as it passes an object that contains both data and functionality, instead of passing back a number of primitive types (such as many strings, or many integers over many properties) to get the same information.

2-8

Introduction to Object-Oriented Programming with Microsoft Visual Studio 2008

Additional Reading
Defining Class Properties

Auto-Implemented Properties (C# Programming Guide)

Controlling Access to Properties



Using Properties (C# Programming Guide) Adding Properties to Your Class

Implementing Classes, Properties and Methods

2-9

Lesson 3

Implementing Methods within a Class


Contents:
Question and Answers Additional Reading 10 12

2-10

Introduction to Object-Oriented Programming with Microsoft Visual Studio 2008

Question and Answers


Defining a Method
Question: How do you decide which methods to include in a class? Answer: The method should perform an action that is part of the class responsibility. A good indication of where to locate a method is to look at the properties modified by the method. Put the method in the class that has the properties that are being modified. Question: What methods might exist on a bank account class? Answer: Answers will vary. Withdraw() and Deposit() are both good answers.

Passing by Reference and by Value


Question: When would you pass a parameter By Reference instead of by Value? Answer: When you want the method called to be able to modify the variable directly.

Overloading
Question: Can you think of a situation where you might use overloading? Answer: Answers will vary. One example is on a method used to retrieve an error message for a multilingual application. One version of the method accepts an error code and returns the error message for the default language, while an overloaded version of the method accepts an error code and a language code, and returns the error message for the specified language. Question: Can you have an overloaded method one of which accepts name and id, the other one accepts id and name? Answer: Yes, as long as name and id are different data types, putting the parameters in a different order is considered a different signature. Question: In Visual Basic, you can have optional parameters. Can you have overloaded methods, one of which accepts name and an optional parameter id, and the other just accepts name? Answer: No, since both methods can accept a single string parameter, the signatures are considered the same. Question: Can you have an overloaded method, one of which accepts name and id, the other one accepts id and name? Answer: Yes as long as name and id are different data types, putting the parameters in a different order is considered a different signature.

Accessors
Question: Can you think of a situation where a method in a class would not be declared as public?

Implementing Classes, Properties and Methods

2-11

Answer: Answers will vary. One example is when you write a method to perform a calculation that is only used within the class.

2-12

Introduction to Object-Oriented Programming with Microsoft Visual Studio 2008

Additional Reading
Overloading

Operator Overloading Usage Guidelines Operator Overloading Tutorial

Implementing Classes, Properties and Methods

2-13

Lesson 4

Using Class Properties and Methods


Contents:
Question and Answers Detailed Demo Steps 14 15

2-14

Introduction to Object-Oriented Programming with Microsoft Visual Studio 2008

Question and Answers


Instantiating a Class
Question: Can you call a method in a class after you have finished declaration? Answer: No, you must instantiate the class before you call the methods in the class. The one exception to this rule is static/shared methods, which are covered later in this module.

Using Properties and Methods


Question: When are the get and set methods for a property called? Answer: The get methods are called when you retrieve a value from the property. The set methods are called when you modify the value of the property.

Shared/Static Properties and Methods


Question: Can you think of an example of a static member you might use at work? Answer: Answers will vary. One example is interest rate on a credit card class. Question: Have you ever used MessageBox? Did you instantiate the MessageBox class before it used the Show method? Why not? Answer: No, because the Show method is a Static/Shared method.

Implementing Classes, Properties and Methods

2-15

Detailed Demo Steps


Demonstration: Using Shared/Static Properties and Methods Detailed demonstration steps
1. Start Visual Studio 2008. Load one of the following solutions based on the language you would like to do the demonstration in: 2. Visual Basic: E:\Allfiles\Demos\Mod02\Lab Starter\VB\ Module2Demo.sln Visual C#: E:\Allfiles\Demos\Mod02\Lab Starter\CS\ Module2Demo.sln

Open the Product class in the Products project in the code view. In the code window you will see two properties defined: ProductID, and ProductPrice. Notice the use of different data types, and which declarations are public and which are private. In the Product class, create a property named ProductName (string) by using a code snippet. (Type prop and press the TAB key twice.) Create a read-only property by un-commenting the RetailPrice property. Highlight the differences between this and a read and write property. Uncomment the first SetRetail method, and review the code. (Do not uncomment the second method as it is used for a later demonstration.) Open the Module2Demo project and add a code reference to Products class library. This is necessary to access the properties and methods of the class library. Open Form1 in the Module2Demo project in the code view, and then navigate to the Button1_Click event handler. Uncomment and review the code. This code creates an instance of the product class and then sets the various properties. Press F5 to execute the application. Click the Create Product button. You should see a message box that displays property values. The code behind the Increase Price (%) button increases the retail price of the product by 10%. Click the button and wait for the execution.

3. 4. 5. 6. 7.

8. 9.

10. Stop the program execution, and return to the Product class. Review the concept of overloading methods, and then uncomment the code for the second method. 11. Return to the code view of Form1 and uncomment the code in Button3_click event handler. Review the code. 12. Press F5 to run the application, and then click the Create Product button and each of the increase price buttons. Review the result. 13. Stop the application from executing. Return to the Product class and review the code for SetTax method. Highlight that it is defined as shared, also the declaration for the _TaxValue variable at the top of the class. 14. Return to the code view of Form1, and uncomment the code in Button4_click event handler. Review the code. 15. Press F5 to run the application and then click on the Shared/Static Demo. Review the results.

2-16

Introduction to Object-Oriented Programming with Microsoft Visual Studio 2008

Module Reviews and Takeaways


Review questions
1. What is the difference between an instance method and a static/shared method? Answer: An instance method can only be called from an instance of a class, and it can access information that is specific to an instance of a class. A static/shared method is shared across all instances of a class, and it can only access properties and fields that are declared as static/shared and are shared across all instances of a class. A static/shared method can be called without creating an instance of the class. 2. How can you create a property that is read-only? Answer: Do not create a set method for the property. In Visual Basic you must also specify the ReadOnly keyword. 3. How are managed resources released when you are finished with a class? Answer: The garbage collector releases the managed resources when it runs. 4. How are unmanaged resources released when you are finished with a class? Answer: Unmanaged resources are not released by the garbage collector, so you should implement the IDisposable interface and add a Dispose method to any classes that use unmanaged resources. Write code in the Dispose method to release the unmanaged resources, and have the programmer using the class call the Dispose method when finished with the class.

Common issues related to creating classes and properties


Identify the causes for the following common issues related to implementing methods and Properties in Classes, and fill in the troubleshooting tips. For answers, refer to relevant lessons in the module.

Issue When I declare a variable to hold my class, the intellisense does not display all the methods and properties I defined in the class. My application is running out of memory. I thought the garbage collector cleaned everything up for me. I found a code example that creates a SqlConnection object, but I do not see anywhere in the code where the connection string is specified for the object. How can it connect without a connection string?

Troubleshooting tip

You have allocated the class, but have not instantiated the class. The garbage collector only releases managed resources. Unmanaged resources such as files need to be released in a finalize or dispose method There is a constructor method for the SqlConnection object that accepts the connection string as a parameter, and sets the property based on the parameter.

Implementing Classes, Properties and Methods

2-17

Real-world issues and scenarios


1. A training company is trying to design their application, and they have determined they need classes for course, student, and registration. Where should they place the CancelCourse, PayRegistration, and RegisterStudent methods? Answer: CancelCourse will update the status property of the course class, so it should be placed in the course class. PayRegistration will update payment date, payment method, and possibly a status property in the registration class, so it should be in the registration class. RegisterStudent is trickier. It creates an instance of the registration class, but it would likely be on the Course class because you would probably create a course object for the course of interest, and then create a registration from the course object. 2. A training company is designing their registration class. They have identified a need for properties to track coursedate, price, paymentMethod, registrationDate, and NbrDaystoCancelWithoutPenalty. Could any of these properties be implemented as shared/static? Answer: NbrDaysToCancelWithoutPenalty could be shared/static. More information is needed to be sure. If all registrations must be cancelled within the same number of days from the course start date to avoid a penalty, then all registrations will have the same value for NbrDaysToCancelWithoutPenalty, and this property can be shared/static. If the number of days from the start date to cancel without penalty varies based on the course taken, the student, or any other instance-specific information, then this property cannot be shared/static. CourseDate specifies the date when a course is running. Although some registrations will have the same course date, not all registrations will have the same course date, so this property cannot be shared/static. Price specifies the price paid for the registration. This will be different depending on the course taken and any discounts the student received for their registration. Not all registrations will have the same price, so this property cannot be shared/static. PaymentMethod specifies whether the registration was paid for by credit card or purchase order. Not all registrations will have the same payment method, so this property cannot be shared/static. RegistrationDate specifies when the student registered for the course. Not all registrations will have the same registration date, so this property cannot be shared/static.

Best practices related to creating classes and properties


Supplement or modify the following best practices for your own work situations: Use properties instead of accessing fields in a class directly. Implement IDisposable for any classes that need to release unmanaged resources. Make sure each class has only one responsibility. Do not try to create a class that does it all. Organize your classes into namespaces.

2-18

Introduction to Object-Oriented Programming with Microsoft Visual Studio 2008

Lab Review Questions and Answers


1. What is the shortcut key for using the property code snippet? Answer: Type prop and press TAB twice. 2. In Exercise 4, why was it not necessary to instantiate the ACustomer variable with the new keyword? Answer: In the next line the GetCustomer method returned an instance of a customer class that was allocated this variable. 3. When using a shared or static method, must you create an instance of the class that the method belongs to? Answer: No, you can use the methods without creating an instance of the class. 4. What is the difference between a solution and a project? Answer: A project is a collection of files (code, configuration and resources) that maps to an assembly. A solution is a method of organising multiple projects that together form a solution. 5. What is the shortcut key for adding a comment snippet? Answer: In Visual Basic it is three apostrophes (). In Visual C# it is three forward slashed (///). 6. Can you name three methods to view the value of a variable while debugging? Answer: While in debug mode you can: 7. Place the cursor over the variable. Create a watch or quick watch. Use the immediate window to query the variable.

Is it possible to set conditions on a break point? Answer: Yes it is, for example when a specific value changes, or when a certain line of code is hit a certain number of times.

Implementing Inheritance, Abstraction, and Polymorphism

3-1

Module 3
Implementing Inheritance, Abstraction, and Polymorphism
Contents:
Lesson 1: Introduction to Inheritance and Abstraction Lesson 2: Implementing Inheritance and Abstraction Lesson 3: Introduction to Polymorphism Lesson 4: Implementing a Polymorphic Structure Module Reviews and Takeaways Lab Review Questions and Answers 2 4 9 11 16 18

3-2

Introduction to Object-Oriented Programming with Microsoft Visual Studio 2008

Lesson 1

Introduction to Inheritance and Abstraction


Contents:
Question and Answers 3

Implementing Inheritance, Abstraction, and Polymorphism

3-3

Question and Answers


Inheritance and Abstraction
Question: Can you think of a situation at work where you could use inheritance? Answer: Answers will vary, but one example is employee and union employee. All employees need to store information about their name and salary. All employees need to be hired or go on leave. However, union employees require extra information to be stored about their union, and grade within the union. Question: What is another class that could inherit from vehicle? Answer: Answers will vary, but could include truck, boat, and bicycle. Question: Can you identify a class that inherits from the car or airplane class? Answer: You could create a sports car class that inherits from car, or a Propeller plane class that inherits from plane. Question: Both SQL and Oracle connections share common functionality and structures. Could you define a common DBConnection class that both inherit? Answer: Yes. Question: What methods/properties might a DatabaseConnection class provide? Answer: Open/Close methods, connectionString property

Benefits of Inheritance
Question: In a procedural language, how do you achieve the benefits of inheritance listed above? Answer: Answers will vary, but generally you use modular code in the form of reusable modules. However, the code that calls the reusable modules is often very dependent on what has been written within the module. Also, the structure created in procedural code does not usually model real life as closely as inheritance.

3-4

Introduction to Object-Oriented Programming with Microsoft Visual Studio 2008

Lesson 2

Implementing Inheritance and Abstraction


Contents:
Question and Answers Detailed Demo Steps Additional Reading 5 6 8

Implementing Inheritance, Abstraction, and Polymorphism

3-5

Question and Answers


Defining Classes Requiring Inheritance
Question: Can you think of a situation where you would implement an abstract class? Answer: Answers will vary based on experience, but one example is bank accounts. Certain characteristics and functionality are common to all bank accounts, but all bank accounts are either savings accounts or checking accounts. You would never create an instance of the bank account class. You create it to reduce code duplication, and to define common functionality in one place.

Inherited Class Construction


Question: Why is it important to call the constructor in the base class? Answer: The constructor in the base class may perform initialization of the properties defined in the base class. Question: Should constructors always call their base class constructor? Answer: No. Only call the base class constructor if you need to call the functionality of the base class constructor.

Shadowing
Question: What is the risk associated with hiding and shadowing? Answer: You may accidentally replace functionality in the base class that needs to be executed. Question: What might be an example of Shadowing? Answer: Answers will vary. When a base class offers a lot of functionality, and the derived class needs to be simplified, then shadowing can offer a benefit.

Sealing
Question: What might be another example of when to implement a Sealed class? Answer: Answers will vary, and will depend on the business rules. In some banks a SavingsAccount might be a sealed class because the only accounts offered are Checking and Savings accounts, and that is the class that should always be instantiated. In another bank the SavingsAccount class might not be sealed, because it is inherited by a HighInterestSavingsAccount class or a JuniorSavingsAccount class.

3-6

Introduction to Object-Oriented Programming with Microsoft Visual Studio 2008

Detailed Demo Steps


Demonstration: Implementing Inheritance Detailed demonstration steps
1. Start Visual Studio 2008, and then load one of the following solutions based on the language you would like to do the demonstration in: 2. 3. 4. Visual Basic: E:\Demos\Mod03\Starter\VB\Mod03Demo\Mod03Demo.sln

Visual C#: E:\Demos\Mod03\Starter\CS\Mod03Demo\Mod03Demo.sln Open the Animal class in the code view, and review the class definition. Open Form1 in the code view, and navigate to the btnDemo1_Click method. Review the definition of the Animal class, and use IntelliSense to demonstrate the available properties and methods of the class. Open the Wolf class in the code view, and review the code. Notice that this class inherits from the Animal class, and that this class has an additional property (Color) defined. Return to the btnDemo1_Click method in Form1, and review the code definition for the Wolf class. Use IntelliSense to demonstrate that the Wolf class contains the properties and methods of its base class as well as the derived class. Press Ctrl+F5 to execute the application. Once the form has been loaded, click the Inheritance button. You should see a message box displaying values from the base and inherited classes. Stop the program application.

5. 6.

7.

Implementing Inheritance, Abstraction, and Polymorphism

3-7

Detailed Demo Steps


Demonstration: Inherited Class Construction Detailed demonstration steps
1. Start Visual Studio 2008, and load one of the following solutions based on the language you would like to do the demonstration in: 2. 3. 4. 5. Visual Basic: E:\Demos\Mod03\Starter\VB\Mod03Demo\Mod03Demo.sln

Visual C#: E:\Demos\Mod03\Starter\CS\Mod03Demo\Mod03Demo.sln Open the Animal class in the code view, and review the class definition. Specifically, notice the constructor. Open the Wolf class in the code view, and review the code. Specifically, notice the draw constructor. Return to the btnDemo1_Click method in Form1, and place a breakpoint in the first line of executable code. Press the F5 key to run the application. Wait for the form to load, and then click the Inheritance button. Step through the code, and make sure you see the messages written to the Immediate window, which will demonstrate the sequence in which the base and derived class constructors are called. Stop the program execution.

6.

3-8

Introduction to Object-Oriented Programming with Microsoft Visual Studio 2008

Additional Reading
Implementing Inheritance

Inheritance Basics

Defining Classes Requiring Inheritance



Abstract (C# Reference) MustInherit

Inherited Class Construction



base First statement of this Sub New must be a call to MyBase.New or MyClass.New (More Than One Accessible Constructor Without Parameters)

Inherited Class Construction

Hiding through Inheritance

Implementing Inheritance, Abstraction, and Polymorphism

3-9

Lesson 3

Introduction to Polymorphism
Contents:
Question and Answers 10

3-10

Introduction to Object-Oriented Programming with Microsoft Visual Studio 2008

Question and Answers


Polymorphism Example
Question: In a procedural language, if you wanted to have code that could call the turn() method for a Car or an Airplane, how would you determine which turn() method to call? Answer: You would have to determine what type is used (i.e., a car or an airplane) and then call the appropriate method. This would usually involve using an if block. The calling code would also need to know about the different types (Car versus Airplane). That means if we change either the car or airplane class, the calling code is likely to change as well. In other words, the caller is very dependent on the code to implement the car and airplane. In the next lesson, you will see how inheritance and polymorphism address this problem.

Implementing Inheritance, Abstraction, and Polymorphism

3-11

Lesson 4

Implementing a Polymorphic Structure


Contents:
Question and Answers Detailed Demo Steps Additional Reading 12 14 15

3-12

Introduction to Object-Oriented Programming with Microsoft Visual Studio 2008

Question and Answers


Polymorphic Casting
Question: Can a variable declared with the type of the derived class hold an instance of the base class? Answer: No, The derived class may implement additional functionality that would not be available in the base class.

Casting with Subtypes


Question: What is the benefit of being able to store an instance of either the base class, or an instance of a class derived from the base class, in a variable or parameter? Answer: It allows you to make your code more reusable so that it can handle new derived classes without any modifications. Question: What is the benefit of having the code treat a subtype like its parent class? Answer: This reduces the need to implement logic to determine the type of vehicle we are using. Question: What is the downside to casting a class as its parent type? Answer: It restricts what you can do with the class to only the base class members. Therefore you cannot call specific methods on the child class type. Instead, you have to determine what type of object it really is, and then cast it as that object. For example, before you can treat a vehicle as an airplane, you have to determine that it is an airplane type first, and then cast the vehicle object as an airplane. At that point, you can refer to members that only exist on the airplane class, and not the vehicle class.

Polymorphic Methods
Question: Can you think of an example where a method is implemented differently in the derived class than in the base class? Answer: Answers will vary, but one example is a bank account and a savings account. A Withdraw method would be defined in the base class bank account, since all account types need to support withdrawing funds. The savings account might charge a transaction fee when a withdrawal is made, so it will implement different functionality for the Withdraw method than its base class bank account. Question: In the example above, does every class have to have override the stop method? Answer: No, only if a better method can be provided. If the derived class does not override the base class, then the version of the method in the base class will be called.

Overrides and Overridable


Question: Is it possible to override a method in the base class if it is not declared with the keyword virtual (Visual C#) or overrides (Visual Basic) in the base class?

Implementing Inheritance, Abstraction, and Polymorphism

3-13

Answer: No, you cannot override it, but you can use hiding and shadowing to change the code executed when you use that method name in the derived class. Question: How do you handle a situation where you have a derived class with a method that should extend instead of replace the functionality defined in the method of the base class? Answer: Override the method in the derived class, and use the keyword base (Visual C#) or MyBase (Visual Basic) to call the method in the base class from the overriding method in the derived class.

Using Polymorphic Methods


Question: Can you think of a situation where new derived types might be added in future releases, and a polymorphic method might simplify maintaining the code? Answer: Answers will vary, but one example is an online store with a product class. Initially a base class of product might be defined with methods such as Reorder, PutOnSale, and RateProduct. Initially there might also be derived classes for DVDs and books. However, in the future the store might decide to add additional products such as Games or Candy. Taking the time to implement a polymorphic method when the application is first developed would simplify supporting the new products in the application. Question: In the example above, what changes would need to be made to the FinishGame method if a new type of vehicle was defined which overrides the Stop Method defined in the Vehicle class? Answer: No changes would be required to the code in the FinishGame method. That is one of the biggest benefits of polymorphic methods. Question: In the example above, what changes would need to be made to the code that calls FinishGame if the method Stop() was renamed in the Vehicle class? Answer: No. Changes would need to be made to the code that calls FinishGame. Only the code within FinishGame would need to be modified. This is another benefit to polymorphic methods.

3-14

Introduction to Object-Oriented Programming with Microsoft Visual Studio 2008

Detailed Demo Steps


Demonstration: Implementing Polymorphism Detailed demonstration steps
1. Start Visual Studio 2008, and load one of the following solutions based on the language you would like to use for the demonstration: 2. Visual Basic: E:\Demos\Mod03\Starter\VB\Mod03Demo\Mod03Demo.sln Visual C#: E:\Demos\Mod03\Starter\CS\Mod03Demo\Mod03Demo.sln

Open the Animal class in the code view, and review the class definition. Recall how the base class was used in the previous demonstration. Pay attention to the Talk function, and how it often happens that an inherited class does not always have the same implementation for a method as the base class. In this case we want a different implementation for the Talk function. Note how the developer of the base class must allow the developer of the derived class to override the implementation of the method in question by specifying the keyword Overridable (Visual Basic) or virtual (Visual C#). Open the Lion class in the code view, and review the code. Notice how the Lion class inherits from the Animal class, and overrides the Talk function. Open Form1 in the code view, navigate to the btnPolymorphism_Click method, and review the code in the method. Press F5 to execute the application. Once the form has loaded, click the Polymorphism button. You should see three message boxes: the first with the base classs implementation of the Talk method which demonstrates inheritance, and the second with the derived classs implementation of the method which demonstrates overriding inheritance. The third messagebox demonstrates polymorphism by utilizing the base class and not referencing the derived classes. Notice the difference between inheritance code and polymorphic code and how polymorphism relies on inheritance. Also notice how the code below the comment //Polymorphic example (Visual C#) or Polymorphic example (Visual Basic) would not change if a different array of objects derived from Animal were passed to it. Stop the program application. Return to the code view of Form1, and place a breakpoint in the first executable line of code in the btnPolymorphism_Click method. Rerun the demonstration as in step 5, but this time step through the code, noticing when the code is in the Animal, Wolf or Lion classes. After the second message box, stop the application execution.

3. 4. 5.

6. 7.

8.

Implementing Inheritance, Abstraction, and Polymorphism

3-15

Additional Reading
Overrides and Overridable

override (C# Reference) Override Modifiers (Visual Basic Programming Guide) abstract (C# Reference)

3-16

Introduction to Object-Oriented Programming with Microsoft Visual Studio 2008

Module Reviews and Takeaways


Review questions
1. When would you override a method in a derived class? Answer: When the functionality of the method in the derived class is different from the functionality of the method in the base class. 2. How can you extend the functionality of a method in a base class from a derived class, instead of replacing it? Answer: Override the method in the derived class, and use base (Visual C#) or MyBase (Visual Basic) to call the method in the base class from the method in the derived class. 3. What type should you use to declare a variable that can hold an instance of a base class or its derived class? Answer: Declare the variable as the base class type.

Common issues related to inheritance, abstraction, and polymorphism


Identify the causes for the following common issues related to inheritance, abstraction, and polymorphism. Then fill in the troubleshooting tips. For answers, refer to relevant lessons in the module. Issue Troubleshooting tip The method was not defined as overridable in the base class. Use the keyword virtual (Visual C#) or Overridable (Visual Basic) in the base class to specify that the method can be overridden. When you declare a variable as the type of the base class, you can only access members in the base class from that variable, even if you store an instance of the derived class in the variable. If you want to call a member of the derived class, you must either cast the variable to the derived class type, or explicitly declare a variable of the derived class, and access the member from that variable.

You receive a warning when you try to override a method in the derived class.

You declare a variable V as the type of the base class, and you assign the variable V to hold an instance of the derived class. When you try to call one of the methods defined in the derived class, you receive an error. You declare two constructors in the base class, one that accepts a single parameter, and one that accepts no parameters. In the derived class, you create a new constructor that accepts a single parameter, but you do not create a constructor that accepts no parameters because you want to reuse the constructor defined in the base class. When you try to instantiate the derived class without passing parameters to the constructor, you receive an error.

Constructors are not inherited by derived classes. If you want to reuse the constructor method that accepts no parameters that is defined in the base class, you must create a constructor in the derived class that accepts no parameters, and use base (Visual C#) or MyBase (Visual Basic) to call the constructor in the base class from the constructor in the derived class.

Real-world issues and scenarios


1. Scenario: You are designing the classes for a book store. You need to be able to store information for online orders placed on the Internet, as well as orders that are placed in the retail stores. All

Implementing Inheritance, Abstraction, and Polymorphism

3-17

orders have an OrderNumber, OrderDate, OrderTotal, and Status, and require a method called PayForOrder. Online orders also require a CustomerName and a ShipOrder method. How would you design the classes for this scenario? Answer: Use inheritance. Define Order as a base class, and put OrderNumber, OrderDate, OrderTotal, Status and the PayForOrder method in the base class. Create a OnlineOrder class that inherits from the Order class, and includes the extra members CustomerName and ShipOrder. 2. Scenario: In the above example should Orders be an abstract class? Answer: It depends. Based on the information provided, we do not need to add a RetailOrder class that is derived from the Order class, because there is no specialized functionality for the RetailOrder class. All the functionality required for retail orders is implemented in the base class, so you would create instances of the Order class directly for retail orders. If upon further investigation you discovered additional properties and methods that only apply to retail orders, then you would create a RetailOrder class, and the Order class would be declared as abstract because you would always create an instance of a RetailOrder or OnlineOrder, never an instance of the Order class directly. 3. Scenario: The book store decides to create a new type of order called Express orders. Express orders are only available online. They have two additional properties: DeliveryCharge, and PromisedDeliveryDate. The PayForOrder method must calculate the payment, and include the delivery charge. How would you implement this class? Answer: You create a new class called ExpressOrders that inherits the OnlineOrder class. You would also override the PayForOrder method in the ExpressOrders class to calculate the payment including the delivery charge.

Best practices for supporting users running applications on Windows XP


Supplement or modify the following best practices for your own work situations: Identify the methods that can be overridden in the base class. Override members instead of shadowing members wherever possible. Use polymorphism to create code that is reusable, and requires less maintenance when new specialized classes are added.

3-18

Introduction to Object-Oriented Programming with Microsoft Visual Studio 2008

Lab Review Questions and Answers


1. Why was it important to return the base class to ensure that the code is polymorphic? Answer: In order to get dynamic execution of the code, the calling code needs to use the base class so it remains agnostic as to which derived class it is referring to. During the execution of the code, whichever derived class is actually contained within the base class will get used making the code polymorphic. 2. What changes within the code within the form would be needed if we added other types of customers with different discount requirements? Answer: No changes would be necessary. This is one of the benefits of creating polymorphic code where the code can be modified without having to modify the code throughout an application. 3. Why was the _discountPercentage variable declared as protected? Answer: The _discountPercentage variable needs to be declared as protected so that the CalculateDiscount method within the derived classes could refer to the internal variable. Another approach would be to keep the variable as private, and use the DiscountPercentage property to access the value from the derived classes.

Implementing Interfaces

4-1

Module 4
Implementing Interfaces
Contents:
Lesson 1: Introduction to Interfaces Lesson 2: Implementing an Interface Module Reviews and Takeaways Lab Review Questions and Answers 2 5 12 14

4-2

Introduction to Object-Oriented Programming with Microsoft Visual Studio 2008

Lesson 1

Introduction to Interfaces
Contents:
Question and Answers 3

Implementing Interfaces

4-3

Question and Answers


Importance of Reducing Code Dependencies
Question: On projects you have worked on in the past, did business requirements often change? Answer: Answers will vary, but generally changes in requirements are to be expected in any application, so there are benefits to reducing code dependencies.

Reducing Code Dependencies through Interfaces


Question: Why would you define an interface for functionality accessed by an external application? Answer: The developers making modifications to the external application should not need to know how exactly you implement the functionality in your application; however, they will be concerned with how to access the functionality in your application. They need to know what properties they can access, what methods can be called, and how to call them. This can all be defined in an interface. Once the interface is defined they can even begin programming their application after the interface is defined.

Importance of Code Standardization


Question: Have you ever worked on an application which had multiple developers writing code? Did you define any standards? Answer: Answers will vary based on experience, but when you have a team of developers co-writing an application, defining programming standards can ensure that all programmers implement similar functionality the same way, and include any required minimum functionality in related classes.

Increasing Code Standardization through Interfaces


Question: Do you need to define exactly how the methods will be implemented when you define an interface? Answer: No, you only need to define the signature of the methods. A signature consists of the method name and its parameters. Question: Can you think of any classes at work that have similar functionality you could standardize through an interface? Answer: Answers will vary based on experience. One example is a banking application that has classes for credit cards, savings accounts, and checking accounts. The bank may allow different types of transactions on the different account types, but all transactions must be logged. You would define an ILoggable interface that in turn defines a method called LogTransaction, which will log information about a transaction.

Discussion: Identify Uses of Interfaces for a Business Scenario


Question: What interfaces would you suggest for this application?

4-4

Introduction to Object-Oriented Programming with Microsoft Visual Studio 2008

Answer: Answers will vary. An ICustomer interface that defines the ID and Name properties for customers would be useful to ensure that customer ID and customer names are stored consistently for retail and online customers. An IProduct interface would be useful to define functionality that must be supported for all product types. The Book and DVD classes would implement this interface, and it could also be implemented for any future products such as games and music CDs. An IOrder interface should be defined to define the common properties and methods for retail and Internet orders. This will make it easier to write reusable code that can record or update either Internet or retail orders.

Implementing Interfaces

4-5

Lesson 2

Implementing an Interface
Contents:
Question and Answers Detailed Demo Steps Additional Reading 6 8 11

4-6

Introduction to Object-Oriented Programming with Microsoft Visual Studio 2008

Question and Answers


Creating an Interface
Question: Why is there no code defined for the methods in the interface? Answer: Interfaces do not contain any implementation code. Instead, they specify properties that must be defined, and the signature of methods that must exist in any classes that implement the interface. The implementation code is included in the class that implements the interface.

Commonly Used System-Defined Interfaces


Question: If you were creating a Customer class and you needed to write a method that allowed you to see if two instances of the customer class represented the same customer, which interface should you implement? Answer: Implement the IEquatable interface and define an Equals method in your class. The Equals method will compare the properties of the two instances to see if they represent the same customer. Question: The IEquatable interface is used to implement a method called Equals that accepts two instances of an object and tells you if the instances are equal. Why would you implement the IEquatable interface instead of just making up your own method in a class to compare two instances, and return a value to indicate if they are equal? Answer: Code standardization. When you implement the IEquatable interface, you are implementing the functionality the same way the .NET Framework implements the functionality. Thus programmers who are used to comparing two instances with the .NET Framework classes that implement IEquatable will already know how to use the Equals method in your class, because it is called with the same signature.

IDisposable
Question: What types of resources are not released by the garbage collector, and should be released in a Dispose method? Answer: Unmanaged resources do not have their memory freed by the garbage collector. Examples of unmanaged resources include file handles, file streams, and resources created through APIs.

Writing Code to Implement an Interface


Question: Why would you create and implement two interfaces, instead of a single interface that defined all the members? Answer: Because two smaller interfaces may be more reusable in other classes. Question: Can a class implement more than one interface? Answer: Yes. It is easier to work with multiple smaller interfaces than one large interface. Smaller interfaces tend to be more reusable.

Implementing Interfaces

4-7

Question: Can a class implement part of an interface? Answer: No, the class must implement the entire interface. Question: Can an interface implement another interface? Answer: Yes, you can create an interface that implements another interface. This can be very useful because you define smaller interfaces to define standard functionality, and then create interfaces that build onto that standard. For example, you could have an IPayable interface that defines standard properties and methods for classes we can pay, such as an employee or contractor. You could then define an IPayableByDirectDeposit interface that implements the IPayable interface and additional properties required to support direct deposit to a bank account.

Interfaces vs. Abstract Classes


Question: If you have some common functionality that you require in a set of related classes, and the requirements for the common functionality are changing frequently, should you implement the common functionality with an interface or an abstract class? Answer: If changes are likely and you expect to add new methods, use abstract classes to implement the common functionality. When you add a new method to an abstract class, its functionality is inherited by all classes that inherit the abstract class. If you add a new method to an interface, you must update all classes that implement that interface to implement the new method.

Polymorphism with Interfaces


Question: What is the benefit of using the interface type for parameters? Answer: The code is more reusable, because it can be handle any class that implements the interface.

4-8

Introduction to Object-Oriented Programming with Microsoft Visual Studio 2008

Detailed Demo Steps


Demonstration: Implementing System Interfaces Detailed demonstration steps
1. Start Visual Studio 2008. Load one of the following solutions based on the language in which you would like to complete the demonstration: 2. Visual Basic: E:\Demos\Mod04\Starter\VB\Mod04Demo.sln Visual C#: E:\Demos\Mod04\Starter\CS\Mod04Demo.sln

Open the Wolf class in the code view, and review the class definition. Uncomment the line that implements the IDisposable interface. a. b. c. Visual Basic: Make sure to press ENTER at the end of the definition line to ensure that the designer will add the code for the required methods. Visual C#: Right-click the IDisposable definition, and then click Implement Interface on the context menu. The comment line raises a new exception. Add the following line: System.Diagnostics.Debug.WriteLine(Dispose method);

3. 4. 5.

Open Form1 in the code view. Navigate to the btnSystemInterfaces_Click event handler. Uncomment the line that invokes the Dispose method. Add a breakpoint on that line. Open the Build menu and click Configuration Manager. In the Active Solution Configuration dropdown select Debug. Click Close. Press the F5 key to execute the application. Once the form loads, click System Interfaces. When the application hits the breakpoint, step through and review the code.

Implementing Interfaces

4-9

Detailed Demo Steps


Demonstration: Defining Custom Interfaces Detailed demonstration steps
1. Start Visual Studio 2008. Load one of the following solutions based on the language in which you would like to complete the demonstration: 2. 3. 4. 5. 6. 7. Visual Basic: E:\Demos\Mod04\Starter\VB\Mod04Demo.sln Visual C#: E:\Demos\Mod04\Starter\CS\Mod04Demo.sln

Open the IWolf interface in the code view, and review the definition. Open the Husky class in the code view, and review the code. Return to Form1 and find btnUserDefInterfaces_Click. Place a breakpoint in the first line of executable code, and then review the code. Press F5 to run the application. Wait for the form to load, and then click the User defined Interfaces button. When the breakpoint is hit, step through the code. Stop the program execution.

4-10

Introduction to Object-Oriented Programming with Microsoft Visual Studio 2008

Detailed Demo Steps


Demonstration: Implementing Polymorphism with Interfaces Detailed demonstration steps
1. Start Visual Studio 2008, load one of the following solutions based on the language in which you would like to complete the demonstration: 2. 3. Visual Basic: E:\Demos\Mod04\Starter\VB\Mod04Demo.sln Visual C#: E:\Demos\Mod04\Starter\CS\Mod04Demo.sln

Open Form1 in the code view. At the bottom of the code, you will find the methods called LoadWolf (accepts a class as a parameter) and LoadIWolf (accepts an interface as a parameter). Navigate to the btnInterfacePoly_Click method, and review the code. Highlight the fact that the method that takes a class must take an instance of the defined class. The second method can take any class that implements the required interface. Place a breakpoint in the first line of executable code, and then press F5 to run the application. Click the Interface Polymorphism button, and step through the code. Notice the difference in the Talk() methods implementation. Stop the program execution.

4. 5. 6.

Implementing Interfaces

4-11

Additional Reading
Creating an Interface

Interfaces (C# Programming Guide) Interface Statement (Visual Basic) Interfaces in Visual Basic

IDisposable

IDisposable Interface Garbage Collection: Automatic Memory Management in the Microsoft .NET Framework Implementing Finalize and Dispose to Clean Up Unmanaged Resources

Writing Code to Implement an Interface



Implements Statement How to: Explicitly Implement Interface Members (C# Programming Guide)

Interfaces vs. Abstract Classes



Inheritance and Interfaces Qualifying .NET Types for Interoperation

4-12

Introduction to Object-Oriented Programming with Microsoft Visual Studio 2008

Module Reviews and Takeaways


Review questions
1. Can a class implement multiple interfaces? Answer: Yes, a class can implement multiple interfaces. 2. How do you implement an interface within a class? Answer: In Visual C#, after the class name, you specify a colon : and then the interface name. In Visual Basic, after the class name, you use the keyword implements, and specify the name of the interface to implement. If you are implementing multiple interfaces, separate the interface names with a comma. 3. What instances of classes can you store in a variable or parameter declared as an interface type? Answer: You can store instances of classes that implement the specified interface type.

Common issues related to interfaces


Identify the causes for the following common issues related to interfaces, and fill in the troubleshooting tips. For answers, refer to relevant lessons in the module. Issue Troubleshooting tip You have not implemented all the required members of the interface. You must implement functionality for each member of the interface that is implemented in your class. Only the methods defined in the interface can be called from a variable that is defined as an interface type. Any additional members defined in the class can only be accessed if you cast the variable or parameter to the class type.

After specifying that your class implements an interface, you receive compile errors when you attempt to build your application. You create a method and decide to use an interface type for your parameter to make your code more reusable. When you write code to call a method of the class you are passing into the method, you receive a compilation error. In a Visual Basic application, you have specified that an interface should be implemented in your class, and you have written the required methods and properties to implement the members of the interface. Yet you still receive compilation errors informing you that your class must implement the methods for the interface.

You have not specified the Implements keyword after the method declaration in your class, to link the method you created to the member of the interface it implements.

Real-world issues and scenarios


1. You are designing an application to track students and their marks for a college. You design a Grade class that is responsible for tracking letter grades, percentage scores, pass and fail status, and a bell-curve method. You need to write code that will rank the grades from different students. What system-defined interface can you implement to help with sorting? Answer: Use the IComparable interface, which defines a CompareTo method. The CompareTo method should compare two instances of the class, and return the larger of the two classes.

Implementing Interfaces

4-13

2.

You are defining an interface for a system boundary. In the first phase of the project, the system boundary must support a ReceiveCustomers method, which will retrieve a list of customers from a file to be imported into the application. In the second phase of the project, a SendOrders method is added to the system boundary, which will create a list of Orders and export them into a file. What methods should be included in the interface during the first phase of the project? Answer: Include both methods in the interface in the first phase of the project. The class that implements the interface can provide a method stub (that does nothing) for the first phase of the project. This prevents you from having to modify the interface in the second phase of the project.

3.

You are defining an interface for classes that implement logging. The interface is called ILoggable, and will define a method called LogMessage. LogMessage requires two parameters: message, and logDestination. There has been a lot of discussion about adding a logSeverity parameter to the method, but due to time constraints, the severity logic has been left out. How should you declare the logMessage method in the interface? Answer: Consider declaring overloaded methods for LogMessage in the interface: one which accepts the message and logDestination parameters, and a second which accepts the message, logDestination and logSeverity parameters. If later in the project the severity logic is added, the interface will not require any modifications.

Best practices related to interfaces


Supplement or modify the following best practices for your own work situations: Define interfaces for functionality that crosses system boundaries. Keep interfaces small and reusable. Define interfaces to avoid having to make changes to the interfaces in the future.

4-14

Introduction to Object-Oriented Programming with Microsoft Visual Studio 2008

Lab Review Questions and Answers


1. What was the method that needs to be implemented in classes that implement the IDisposable interface? Answer: Dispose() 2. Can the interface implementation span multiple classes? Answer: Yes. In the lab we used an inheritance structure to represent all the properties and methods of the RetailCustomer class. However, we had one interface definitionIRetailCustomer. 3. When defining a method, what can we do to ensure that the parameters are not bound to a specific class? Answer: User interfaces as the parameter. Then you can use any class that implements that interface.

Designing Object-Oriented Structures

5-1

Module 5
Designing Object-Oriented Structures
Contents:
Lesson 1: Establishing Classes from Business Requirements Lesson 2: Adding Inheritance to the Design Lesson 3: Adding Interfaces to the Design Lesson 4: Reviewing and Refining the Design Module Reviews and Takeaways Lab Review Questions and Answers 2 9 13 16 19 21

5-2

Introduction to Object-Oriented Programming with Microsoft Visual Studio 2008

Lesson 1

Establishing Classes from Business Requirements


Contents:
Question and Answers Detailed Demo Steps Additional Reading 3 6 8

Designing Object-Oriented Structures

5-3

Question and Answers


Goals of Object-Oriented Design
Question: How have you approached application design in the past? Answer: Answers will vary. However, the key point to remember is that spending time designing the application saves time and money in development, testing, and production. It is easier to update a design than to update code in development, to make a change during testing, or to make a change after it goes into production. Taking time up front to complete design will reduce the overall cost of the application. Question: If you create a design focused on reusable code, how can you modify the code without making every change global? Answer: Use derived classes and override methods in the derived classes that will be called when needed. Or, use overrides/polymorphism, and let object-oriented design do its job.

Creating a Class Diagram


Question: Why is important to create a class diagram? Answer: A class diagram can be more easily read by others, and can provide quick access to the various types used by an application. Question: Should you create more than one diagram within a project? Answer: It is important that diagrams be clear and concise. If a diagram becomes too large, consider dividing your diagram into multiple diagrams to better reflect the key areas of your application.

Design Approaches
Question: What tools have you used in the past to document your design? Answer: Answers will vary based on experience.

Identifying Classes, Properties, and Methods from Business Requirements


Question: Could we use a boolean property Preferred on the customer class to represent that the customer is preferred? Answer: Yes, but if preferred members have extra functionality such as a PlaceOrderWithoutCreditCard(), how do we add that to the customer class? Because of the extra functionality, we need to represent the preferred class by its own class. Question: How do you determine if an adjective should be a Property or a Derived Class? Answer: It depends on whether the adjective requires additional functionality. When in doubt, add it as a Property since it is simpler. If you discover additional requirements later, you can make it a derived class.

5-4

Introduction to Object-Oriented Programming with Microsoft Visual Studio 2008

Identifying Classes from Business Requirements


Question: What is the responsibility of the products class? Answer: The product class manages the list of products. Question: Should the product class have all of the database connectivity codesuch as Connection.open()inside of it? Answer: No. It is not the product class responsibility to know about databases. Its responsibilities include: managing the list of products, sorting the list, and getting an individual product. Question: Which class will get the products list from the database? Answer: One possibility is a ProductTable class. Its responsibility is to interface between the products table in the database, and the product entity, or Products entities in this case. In a more advanced solution, the actual connection is probably managed by a data abstraction layer (DAL) type class that connects to the database. So, products go to ProductTable, which goes to the DAL, which goes to the database. Question: Consider the responsibility of the order class within the slide. Should it manage the current inventory levels? Answer: No. It is not its responsibility. We should consider a warehouse class to manage that responsibility.

Discussion: Identifying Classes, Properties, and Methods from Business


Question: What candidate classes, properties, and methods can you identify from this business scenario? Answer: Answers will vary, but possible candidate classes include: Course, Session, Registration, Student, and Instructor. Methods and properties will also vary, but possible properties and methods for the candidate classes are listed below. You may identify additional properties and methods based on assumptions that the business requires more than the requirements listed in the short scenario described above. Course Session Properties: Course, StartDate, Status, Instructor Methods: ScheduleSession, ConfirmSession, CancelSession, AssignInstructor Properties: Code, Name, Description, Price Methods: AddCourse, RemoveCourse

Registration Properties: Student, Session, Course, Price, PaymentMethod, Status Methods: RegisterStudent, PayForRegistration, CancelRegistration

Student

Designing Object-Oriented Structures

5-5

Properties: Name, EmailAddress, PhoneNumber, Company Methods: AddStudent

Instructor Properties: Name Methods: AddInstructor

Question: What candidate classes, properties, and methods can you identify from this business scenario? Answer: Answers will vary, but possible candidate classes include: Course, Session, Registration, Student, and Instructor. Methods and properties will also vary, but possible properties and methods for the candidate classes are listed above. You may identify additional properties and methods based on assumptions that the business requires more than the requirements listed in the short scenario described in the student manual.

5-6

Introduction to Object-Oriented Programming with Microsoft Visual Studio 2008

Detailed Demo Steps


Demonstration: Creating a Class Diagram Detailed demonstration steps
Create a new class library project
1. 2. In Visual Studio 2008, create a new class project named ClassDiagramDemo. Delete the file Class1.cs (Microsoft Visual C#) or Class1.vb (Microsoft Visual Basic).

Add a new class to the class library project


1. 2. Add a new class file to your project named Person.cs (Visual C#) or Person.vb (Visual Basic). Within the Person class, add a string property called Name, and a method called Update that returns a Boolean. Your code should resemble the following.

[Visual C#]
public String Name { get; set; } public boolean Update() { return false; }

[Visual Basic]
Public Property Name() As String Get End Get Set(ByVal value As String) End Set End Property Public Function Update() As Boolean Return False End Function

3.

Close the file Person.cs (Visual C#) or Person.vb (Visual Basic).

Add a class diagram


Add a class diagram to the ClassDiagramDemo project.

Add an existing class to the class diagram


Add the file Person.cs (Visual C#) or Person.vb (Visual Basic) to the diagram.

Add a new class using the class diagram


Using the class diagram, add a class called Student to the diagram.

Add a method to a class within the class diagram


1. 2. Using the class diagram, add a method called OrderTranscript to the Student class. Add a parameter named official that is of Boolean type.

Designing Object-Oriented Structures

5-7

Add a property to a class within the class diagram


1. 2. 3. Using the class diagram, add a property named Year to the Student class by right-clicking the Student class. Using the class diagram, add a property named Graduated to the Student class using the Class Detail pane. Save the project. Note: You will be using this project within the next demonstration in this module.

5-8

Introduction to Object-Oriented Programming with Microsoft Visual Studio 2008

Additional Reading
Class Diagrams

Visual Studio 2005 Class Designer

Design Approaches

UML Notation Microsoft Office Visio 2007 Product Overview The Nordic Object/Relational Database Design

Designing Object-Oriented Structures

5-9

Lesson 2

Adding Inheritance to the Design


Contents:
Question and Answers 10

5-10

Introduction to Object-Oriented Programming with Microsoft Visual Studio 2008

Question and Answers


Adding Inheritance to a Class Diagram
Question: Since you can chose whether or not you display a base class, why would it be important to show inheritance in a class diagram? Answer: By displaying the inheritance structure, other developers can better choose which classes they utilize within their code. Question: Does representing the inheritance relationship visually within the class diagram help with designing an application? Answer: Yes. By visually representing the inheritance model during design, developers can better represent their models, discuss them, and establish better solutions to a problem.

Identifying Inherited Class Structures from Business Requirements


Question: What is a helper class example? Answer: A helper class provides very common methods to design, such as math calculations. Question: Is it better to use helper classes or regular classes? Answer: Regular classes provide better business functionality in general, and tend to offer better inheritance models. Consider using them first before using helper classes.

Discussion: Identifying Inheritance Class Structure


Question: What opportunities are there in this application to use inheritance? What base classes and derived classes can you identify? Which properties and methods should be in the base class, and which properties and methods should be in the derived classes? Answer: Answers will vary, but may include creating a base class of Session, with derived classes for Public and Dedicated Sessions. A base class can also be created for Instructor, with derived classes for Contractor and Staff Instructor. Your answer should identify the changes to be made to the class design from the following class diagram.

Designing Object-Oriented Structures

5-11

Possible methods and properties for these base and derived classes include: Session Properties: Course, StartDate, Status, Instructor Methods: ScheduleSession, ConfirmSession, CancelSession, AssignInstructor

Public Session Properties: AdvertisedPrice Methods: none identified

Dedicated Session Properties: SixToTenStudentDiscount, MoreThanTenStudentDiscount, Company Methods: none identified

Instructor Properties: Name Methods: AddInstructor

Staff Instructor Properties: none identified Methods: none identified

Contractor Properties: City, DailyRate Methods: none identified

Discussion: Refining Properties and Method Placement


Question: Where should the price be stored? Answer: Price should be stored in the Session base class, because a price must be stored for all sessions, both dedicated and public.

5-12

Introduction to Object-Oriented Programming with Microsoft Visual Studio 2008

Question: If the company offers discounts on the price depending on the number of students attending a dedicated course, and also offers a discount on public course sessions in the summer to increase attendance, where should discount be stored? Answer: The discounts are calculated differently for dedicated courses, so the discount should be stored in the derived class DedicatedSession. This way, you can store the discount for more than five students, and the discount for more than ten students. You should also store a discount in the derived class PublicSession. You may want to ask the company if the summer discounts apply to the dedicated sessions as well, in which case discount should be stored in the base class Session, instead of in the Public Session class. Question: Where should the method ScheduleSession be stored? Answer: You may need more information from the business to find out where to store ScheduleSession. Are there different business rules that must be followed when scheduling a public session or a dedicated session? They may be stored in different database tables. Find out if instructors are scheduled immediately for dedicated sessions, while public sessions only have instructors scheduled if they have three or more students registered. If the business rules are the same for both types of sessions, then the method should be listed in the Session class. .If the rules are completely different for both types of sessions, then the method should be listed in the derived classes, PublicSession and DedicatedSession. If the method has some common functionality and extra steps required for public and dedicated sessions, then you should list the method in both the base and derived classes, and when you implement the method in the derived class, you will call the method in the base class. Question: Are all the properties and classes in the proper place? Answer: Answers will vary based on the solution designed. Properties should be in the base class if they apply to the base class and all derived classes. Properties should be in the derived classes where they are required, if they do not apply to the base class and all derived classes. Question: Is inheritance used properly? Answer: Answers will vary based on the solution designed. Inheritance should be used when there are classes with similar common functionality.

Designing Object-Oriented Structures

5-13

Lesson 3

Adding Interfaces to the Design


Contents:
Question and Answers 14

5-14

Introduction to Object-Oriented Programming with Microsoft Visual Studio 2008

Question and Answers


Adding Interfaces to a Class Diagram
Question: Should you add every implemented interface to a class diagram? Answer: Only if it adds clarity. Generally, not every implemented interface would be shown within a class diagram. For example, system-defined interfaces are often not shown. If a diagram is complicated, other developers will have difficulty finding the information they need from it. Consider using multiple diagrams instead. Question: Why is it important that Microsoft .NET support refactoring? Answer: Code evolves over time. Therefore, it is important that tools and features exist that support the moving and redefining of existing code.

Identifying Interfaces from Business Requirements


Question: What is the benefit of implementing the IPayable interface? Answer: It allows for Employees and Customer to be simply treated as things we pay, and since we can treat them the same way, we can process all of the checks together if we want.

Discussion: Identifying Interfaces from Business Requirements


Question: Based on these requirements are there any interfaces you should add to the design? Answer: An IContractor interface should be defined that identifies the properties and methods for the Contractor class, since this class is accessed across a system boundary. Properties might include: Name, PhoneNumber, City, and EmailAddress. Methods might include AddToListOfContractors. An ISchedulableEvent interface should be defined that identifies the properties and methods that must be supported by any event that can be scheduled, such as a session, workshop, or seminar. Properties might include: Name, Duration, Description, and Price.

Discussion: Refining the Class Diagram to Include Interfaces


Question: What classes should implement the ISchedulableEvent interface? Answer: Answers may vary. One possible solution is the course class should implement the ISchedulableEvent interface. Another possible solution is creating a class hierarchy for courses, seminars, and workshops, in which case you could implement the interface for the base class of the hierarchy. Question: What classes should implement the IContractor interface? Answer: The Contractor class should implement the IContractor interface. Question: Are there any properties or methods that should declare the interface type?

Designing Object-Oriented Structures

5-15

Answer: Answers may vary, but the Course property of the Session class that keeps track of what course a session scheduled could be of type ISchedulableEventInterface. This would allow the Session class to track sessions for seminars and workshops, as well as courses. Question: Will the interface be able to handle updates? Answer: Answers will vary. We are already preparing for updates by designing the interface to handle workshops and seminars.

5-16

Introduction to Object-Oriented Programming with Microsoft Visual Studio 2008

Lesson 4

Reviewing and Refining the Design


Contents:
Question and Answers 17

Designing Object-Oriented Structures

5-17

Question and Answers


Discussion: Validating and Evaluation a Proposed Design
Question: What improvements could be made to the design? Answer: Answers will vary, but the following are a few areas where improvements could be made. Do you need the publicSession class? There are no methods and properties in the publicSession class that are different from the Session class. Any public sessions could be implemented by creating an instance of the Session class. The properties for discounts on dedicated sessions are very restrictive. It is not unlikely that the discounts and the number of students required to receive discounts could change. It may be better to define a Discount class with properties called DiscountAmount, LowerLimit, and UpperLimit, and associate a discount with the dedicated sessions. This way, if the business rules change for applying discounts, the changes can be made in the discount class. The discount class could also be made reusable for applying discounts to the summer sessions discounts. Do you need the StaffInstructor class? You might discover there are additional properties and methods for staff instructors, such as Salary. If these properties are required for the application, you can keep the StaffInstructor class and add appropriate methods and properties to the class. If there are no properties and methods unique to StaffInstructor, remove the class, and use the base class Instructor to provide the functionality for staff instructors. There is an opportunity for an additional interface called IContact. Contact information such as e-mail address, name, and phone numbers are stored for students and contractors. You could define an interface to implement those properties and methods. Would this replace the IContractor interface? That depends. Are there other methods and properties we need to expose in the IContractor interface that would not apply to students? Keep in mind the IContractor interface was created to define an interface across a system boundary, so it may define methods and properties that are unique to contractors. The IContractor interface could implement the IContact interface.

Future Considerations for Design


Question: Can you think of any future considerations that might affect the training company scenario? Answer: Answers will vary. One future consideration is the seminars, and workshops. You might decide to create an inheritance structure around courses, with a base class for EventsToSchedule and derived classes for courses, workshops, seminars, and courses. Or you could create workshop and seminar classes that implement the ISchedulableEvent interface, and associate the session class with the ISchedulableEvent interface. One technology consideration is the database. The current class design is tightly coupled to the database. Using the existing classes as a business layer, and adding classes to act as a data layer would decouple the database technology. Classes could be added for each business class that is stored in a database table. The data layer classes would connect to the database, and contain the methods for executing Select, Insert, Update, and Delete commands against the database. The

5-18

Introduction to Object-Oriented Programming with Microsoft Visual Studio 2008

business layer classes would instantiate the data layer classes, and execute the methods to access the database as needed. One common functionality between applications consideration is error logging. You may want to define an error handling class that will handle and log any errors that are raised by the classes during execution. This class could be reused in other .NET applications.

Designing Object-Oriented Structures

5-19

Module Reviews and Takeaways


Review questions
1. When should you add an interface to a class diagram? Answer: You should add an interface when you have common functionality you want to define across classes that are not related through inheritance, or you want to define the functionality available across a system boundary. 2. How do you decide whether to place a property in the base or derived class? Answer: If the property is required for all the derived classes, you put the property in the base class. If the property is only required for some of the derived classes, you put it in the derived classes that require the property. 3. Can you implement multiple levels of inheritance? For example, can I define a Microsoft instructor as a type of staff instructor as a type of instructor? Answer: Yes, you can include multiple levels of inheritance in a class diagram and in your .NET application.

Common issues related to designing object-oriented solutions


Identify the causes for the following common issues related to designing object-oriented solutions, and fill in the troubleshooting tips. For answers, refer to relevant lessons in the module. Issue You are designing a solution for an airline company, and you need to track the passengers on flights. You have identified the need for a passenger and a flight class. You are having difficulty deciding where to store the price paid by the passenger for a particular flight. You are designing a solution that shows the orders placed by customers. You have identified the need for a Customer class and an Order class. You have an association between Customer and Order, so each order stores an instance of a customer. However, you are not sure how the application will be able to list all the orders placed by a customer. Troubleshooting Tip

You are missing a class. You should add a ticket class that would store the price paid by a particular passenger for a particular flight. When you have a property that could have multiple values for an instance of a class, you may be missing a class.

You should add a new class called Orders. The Orders class contains a property called Orders that is a collection of instances of the Order class. You can associate the Customer class with the Orders class so that you can see all the orders placed by a particular customer.

You are designing your classes, and you are having trouble identifying the methods to implement in the classes. It seems like every class just has three methods called Add, Update, and Delete.

Are you designing a data layer class that will be sending Insert, Update, and Delete statements to the database? If so, the methods you have defined are reasonable. If you are defining business layer classes, the method names should reflect the business process or task being performed. For example, a cancelTicket method in a ticket class is updating the status property of a ticket class, but the name UpdateTicket does not indicate the business function being performed as clearly as cancelTicket.

5-20

Introduction to Object-Oriented Programming with Microsoft Visual Studio 2008

Real-world issues and scenarios


1. You are designing classes that will be used in the data layer of an application. You have defined a CustomerDB class that reads from and updates the Customer table in the database. You have also defined a ProductDB class that reads from and updates the Product table in the database. You find yourself having to specify the connection string to connect to the database in each of the data layer classes, and you are concerned about how much code will need to be modified if the database connection information changes. What should you do? Answer: You could define a database connection class that can be called from the data layer classes. It could have a method called GetConnection, which returns a database connection to the data layer classes. With this solution, only one class needs to be updated if the database connection information changes. You can also have the database connection class read the database connection string from a configuration file, so it can be updated after deployment without any code modifications. 2. You are designing an application for a bank. The bank offers a variety of account types, including checking accounts, high interest checking accounts, student checking accounts, savings accounts, junior savings accounts, and senior savings accounts. How would you represent this in a class diagram? Answer: Define a base class called account, with derived classes for SavingsAccount and CheckingAccount. Define HighInterestCheckingAccount and StudentCheckingAccount classes as classes derived from CheckingAccount. Define JuniorSavingsAccount and SeniorSavingsAccount classes as classes derived from the SavingsAccount class. 3. You are designing an application for a bank. You have identified classes for Customer and Account. The bank has indicated they need to store a maximum withdrawal limit. Where should you add this property? Answer: You need more information. Is the daily withdrawal limit dependent on the account? If so, it should be a property of the account class. Does the daily withdrawal limit depend on the customer? If so, it should be a property of the customer class.

Best practices related to designing object-oriented solutions


Supplement or modify the following best practices for your own work situations: Identify interfaces for system boundaries. Consider future needs and changes when completing your class design. Use inheritance to define commonality between related classes.

Tools
Tool Use for Creating class diagrams and code generation Creating class diagrams and code generation Where to find it

Office Visio Visual Studio 2008 Class Designer

http://office.microsoft.com/enus/visio/default.aspx

Built into Visual Studio 2008

Designing Object-Oriented Structures

5-21

Lab Review Questions and Answers


1. Why is it important to identify the responsibility of each class during the design phase? Answer: Identifying the responsibility of each class helps to focus the purpose of each class, and to provide a method of validation as we introduce changes into the design. The question Should this method exist with this class? is answered by validating if it fits within the boundary of the responsibility/purpose of that class. 2. What is the advantage of using an inheritance structure versus adding logic code to a single class? Answer: An inheritance model has the advantage of introducing change with less impact on existing code. By leveraging polymorphism, new class structures and new behaviors can more easily be added without modifying runtime code. 3. What is the impact of changing an interface definition after it has been implemented within code? Answer: Each class that implements the interface will have to be modified to introduce any changes to the interface definition that was introduced. 4. What is the difference between validating the design and evaluating the design? Answer: Validating the design is focused on ensuring that the design will fulfill the business criteria from a functional standpoint. Evaluating the design is focused on determining if the design both fulfills a best-practice approach and considers future goals as well as the impact of the design upon those goals.

Delegates, Events and Exceptions

6-1

Module 6
Delegates, Events and Exceptions
Contents:
Lesson 1: Introduction to Delegates Lesson 2: Implementing Delegates Lesson 3: Introduction to Events Lesson 4: Implementing Events Lesson 5: Introducing Exceptions Lesson 6: Implementing Exceptions Module Reviews and Takeaways Lab Review Questions and Answers 2 5 11 13 18 20 26 28

6-2

Introduction to Object-Oriented Programming with Microsoft Visual Studio 2008

Lesson 1

Introduction to Delegates
Contents:
Question and Answers Additional Reading 3 4

Delegates, Events and Exceptions

6-3

Question and Answers


Introduction to Delegates
Question: What is the advantage of having a middle tier between two communicating parties? Answer: The middle tier decouples the code, so that one class can invoke functionality without knowing where that functionality is located. You could change the functionality executed without changing the calling code.

The Delegate Model


Question: Could a single power button turn on multiple devices? Answer: Yes, that is a multicast delegate. Each callback method that turns on a device can register itself to the delegate object, and the button only has to call one delegate to invoke all the callback methods. Question: If we wanted to use a button to turn on a new device, would we have to modify the code in the Switch Object to handle the new device? Answer: No, as long as the signature of the callback method that we call to turn on the new device, is the same as the signature of the delegate. Question: Controlling many types of objects similar to the television or DVD player requires them to call methods that match the delegate signature. Is there a way to help standardize the method calls to ensure they use a particular signature? Answer: Yes, use an interface.

6-4

Introduction to Object-Oriented Programming with Microsoft Visual Studio 2008

Additional Reading
Introduction to Delegates

Delegates (C# Programming Guide) Delegates in Visual Basic

Delegates, Events and Exceptions

6-5

Lesson 2

Implementing Delegates
Contents:
Question and Answers Detailed Demo Steps Additional Reading 6 8 10

6-6

Introduction to Object-Oriented Programming with Microsoft Visual Studio 2008

Question and Answers


Defining a Delegate Type
Question: Why is there no implementation code for the delegate? Answer: The delegate acts as a function pointer. When you declare a delegate, you specify the method signature that the delegate will reference. You do not implement the method within the delegate declaration.

Invoking a Method by Using a Delegate Instance


Question: When would you use a synchronous call instead of an asynchronous call? Answer: Answers will vary, but synchronous calls usually involve situations where the code cannot continue execution because it requires the functionality of the called method to complete before it can continue. Question: When would you invoke a delegate asynchronously with a callback method? Answer: Answers will vary, but usually involve methods that take a long time to execute. One example is using a delegate to invoke a method that updates a series of database records based on a lengthy calculation, and then using a callback method to launch a report when the database updates complete.

Delegates
Question: What changes would you need to make to the button1_Click method if more delegate callbacks were registered? Answer: No changes are needed. Question: What would the button1_Click method look like if delegates were not used? Answer: Most likely, the button1_Click method would directly call each method. Therefore, as the method list changed, the button1_Click method would have to be updated as well. To dynamically register/unregister the methods from being called, each method call would likely be wrapped within if statements. 1. 2. 3. 4. Run the project in debug mode. Check Register Class 1 Delegate and step through the code. Check Register Class 2 Delegate and step through the code. Click Invoke Delegate, and step through the code.

Question: What is the advantage of using a multicast delegate? Answer: A multicast delegate has the advantage of separating the delegate registration/deregistration of multiple methods away from the code that calls the delegate.

Delegates, Events and Exceptions

6-7

Question: In the Method Selection part of the demonstration, what is the difference from using a delegate to help determine which method to invoke versus using logic statements to determine which method to invoke? Answer: By using a delegate, the code that invokes the delegate will not require updating if the list of methods changes.

6-8

Introduction to Object-Oriented Programming with Microsoft Visual Studio 2008

Detailed Demo Steps


Demonstration: Delegates Detailed demonstration steps
Review a Multicast Delegate
1. 2. Log on to 6367A-LON-SVR1 as Administrator using the password Pa$$w0rd. Using Visual Studio 2008, open the solution located at: 3. Visual C#: E:\Demos\Mod06\Starter\CS\DelegatesDemo\DelegatesDemo.sln Visual Basic: E:\Demos\Mod06\Starter\VB\DelegatesDemo\DelegatesDemo.sln

Within Form1.cs for Visual C# or Form1.vb for Visual Basic, find the delegate type declaration for DelegateNotify. Examine the delegate type declaration, and notice how it matches the signature of the methods to invoke. Examine the instance declaration NotifyList of the delegate DelegateNotify type on the following line. Examine the code within the checkBox1_CheckedChanged method. Notice how the method registers C1.SendMessage to the delegate. Move to the checkBox2_CheckedChanged method. Examine how the method registers c2.NotHelloWorld. Notice how the methods have no parameters, and the methods being called in c1 and c2 do not have to be named the same, but need the same parameter list. Also notice how these methods need to match the delegate type DelegateNotify declared above. Show the code within the button1_Click event handler method. Examine how this method is unaware of what methods are being called, or the number of methods being called. Remember that we should check that there is at least one method to call before invoking the delegate instance. Open class1.cs and show the SendMessage method. Open class2.cs and show the NotHelloWorld method.

4. 5. 6.

7.

8. 9.

10. In Form1.cs for Visual C# or Form1.vb for Visual Basic, set a breakpoint on the following methods: button1_Click checkBox1_CheckedChanged checkBox2_CheckedChanged

Review a Delegate Configured for Method Selection


1. 2. 3. 4. Examine the file Utilities.cs for Visual C# or Utilities.vb for Visual Basic. Examine how both methods have the same number and type of parameters. Close Utilities.cs. Within Form1.cs for Visual C# or Form1.vb for Visual Basic, expand the region titled Method Selection Demo. Examine the delegate type declaration of ProcessList and the parameter list.

Delegates, Events and Exceptions

6-9

5.

Examine the code within the doProcess method. Notice how the parameter is a delegate instance called delProcessList, and is of type ProcessList. Notice how the method simply invokes the delegate instance delProcessList. Examine the code within the button2_Click method. Notice how the button2_Click method passes new delegate created from the SortIt method to the doProcess method. Notice how the button3_Click method does the same thing as the button2_Click method, but passes the ReverseIt method instead. Run the project. Click on the Sort List and String Reverse buttons. Notice how any method that matches this signature could be passed to doProcess, and manipulate the list without affecting the code within the doProcess method.

6. 7. 8. 9.

10. Close the project.

6-10

Introduction to Object-Oriented Programming with Microsoft Visual Studio 2008

Additional Reading
Defining a Delegate Type

Using Delegates (C# Programming Guide) A Primer on Creating Type-Safe References to Methods in Visual Basic .NET

Instantiating a Delegate

How to: Declare, Instantiate, and Use a Delegate (C# Programming Guide) Delegates and the AddressOf Operator

Invoking a Method by Using a Delegate Instance



Asynchronous Programming Using Delegates Asynchronous Programming Overview

Delegates, Events and Exceptions

6-11

Lesson 3

Introduction to Events
Contents:
Question and Answers 12

6-12

Introduction to Object-Oriented Programming with Microsoft Visual Studio 2008

Question and Answers


The Event Model
Question: Can you think of an event you might raise in a business scenario? Answer: Answers will vary. One example could be a bank account class that might raise a maximum withdrawal limit reached event when someone attempts to withdraw more than their maximum daily withdrawal limit.

Delegates, Events and Exceptions

6-13

Lesson 4

Implementing Events
Contents:
Question and Answers Detailed Demo Steps Additional Reading 14 15 17

6-14

Introduction to Object-Oriented Programming with Microsoft Visual Studio 2008

Question and Answers


Raising a Custom Event
Question: What happens when the event is raised? Answer: If no event handlers have been created for the event, nothing happens. If code somewhere in the application has registered an event handler for this event, that event handler will execute when the event is raised. Question: Do you always pass parameters to an event? Answer: No. If the event was declared using parameters, you must pass values for the parameters when you raise the event. You can create a custom event with no parameters, in which case you would not pass any parameters when the event is raised.

Events
Question: Why would you want to define your own events within your classes? Answer: By defining your own events within your classes, you can better represent the existing business structures. Also, the classes will better encapsulate their own functionality. For example, an order object that raises its own OrderChanged event requires less logic in other parts of an application to determine if the order has changed. Question: Should custom events use the same parameters as system-defined events? Answer: Custom events are not required to use the same parameters as system-defined events. However, many developers will use the same parameters to provide some consistency in how events are used within their application.

Delegates, Events and Exceptions

6-15

Detailed Demo Steps


Demonstration: Events Detailed demonstration steps
Add an Event Handler for a Built-in Event
1. 2. Log on to 6367A-LON-SVR1 as Administrator using the password Pa$$w0rd. Using Microsoft Visual Studio 2008, open the solution located at: 3. 4. 5. 6. 7. 8. Visual C#: E:\Demos\Mod06\Starter\CS\EventsDemo\EventsDemo.sln Visual Basic E:\Demos\Mod06\Starter\VB\EventsDemo\EventsDemo.sln

Build the project. Open Form1.cs (Visual C#) or Form1.vb (Visual Basic) from the Solution Explorer. Examine the form. Add a button to the bottom, right hand corner of the form with a text property of Modify OrderItem. Double-click the button. Examine the parameters of the button1_Click method. In the button1_Click method, add code to display the text Modify OrderItem has been clicked in a message box. Examine how the event handler is registered. Note: Visual C# only: Press CTRL+F, and then type this.button1.Click. Change Look in: to Entire Solution, and then click Find Next. Point out to students how double-clicking the button added this code automatically.

9.

Run the project.

10. Click Modify OrderItem. Examine how the event handler code was called.

Add an event handler to an object


1. Within Orders.cs (Visual C#) or Orders.vb (Visual Basic) expand the OrderItem class. Visual C# only: Examine the public delegate declaration ChangedEventHandler. In both Visual C# and Visual Basic, examine the event declaration PricingChanged. Examine the OrderQty property. Notice how any change to this property raises the event by calling RaisePricingChanged, which fires the event by calling PricingChanged(this). Expand the default constructor for the Order class. In Visual Basic only: Modify the orderItem and orderrItem2 declarations to allow for events. Add a default event handler for the orderItem.PricingChanged event. Configure this event handler to also handle the orderItem2.PricingChanged event. If you are using Visual Basic, ensure the orderItem2.PricingChanged event is registered using AddHandler. Add an Event Declaration to an Object

2. 3. 4. 5.

6-16

Introduction to Object-Oriented Programming with Microsoft Visual Studio 2008

Near the top of the Order class below //TODO add event declarations, add an event named OrderChanged. For Visual C#, name the delegate OrderChangedEventDelegate. Add Code to Raise an Event In the orderItem_PricingChanged method, raise the event. For Visual C#, remember to check that OrderChanged is not empty.

Add an event handler to a form


1. Within Form1.cs (Visual C#) or Form1.vb (Visual Basic) add a default event handler for the order.OrderChanged event. For Visual C#, you can add the registration code to the Form1_Load method. For Visual Basic, remember to modify the declaration of order to allow event handling. In the order_OrderChanged method, add code to display a $ concatenated to the order.OrderTotal property within label1. Run the project. Test by changing the order quantity of one of the order items. The order total price should reflect the new total price.

2. 3. 4.

Delegates, Events and Exceptions

6-17

Additional Reading
Creating System Event Handlers

EventHandler Delegate WithEvents and the Handles Clause

Creating a Custom Event



Events Tutorial (C# Programmers Reference) How to: Add Events to a Class

Creating a Custom Event

Raising an Event

Handling a Custom Event



How to: Connect Event Handler Methods to Events AddHandler and RemoveHandler

6-18

Introduction to Object-Oriented Programming with Microsoft Visual Studio 2008

Lesson 5

Introducing Exceptions
Contents:
Question and Answers 19

Delegates, Events and Exceptions

6-19

Question and Answers


The Exception Model
Question: Why would you pass the exception to the calling class instead of handling the exception entirely within your own class? Answer: If the calling class has called a method in your class to perform a particular action, it is important that the calling class is aware that the desired action could not be completed. If the exception raised prevents the method from completing its task, you need to either pass an exception up to the calling class, or you design your method to use a parameter or return value to return an error code to the calling class.

6-20

Introduction to Object-Oriented Programming with Microsoft Visual Studio 2008

Lesson 6

Implementing Exceptions
Contents:
Question and Answers Detailed Demo Steps Additional Reading 21 23 25

Delegates, Events and Exceptions

6-21

Question and Answers


Handling Exceptions
Question: If you have multiple catch statements, does it matter in what order you list the catch statements? Answer: Yes. You should list the catch statements starting with the most specific exceptions you want to catch, and ending with the most generic exceptions. The first catch statement that matches the exception thrown will handle the exception.

Creating Custom Exceptions


Question: When would you create a custom exception? Answer: Answers will vary, but you can use custom exceptions to indicate when a business rule has been violated. For example, you could raise an InsufficientFundsException when someone attempts to withdraw an amount of money from a bank account that exceeds their account balance.

Throwing Exceptions
Question: How can you handle an exception in your code, and still pass the exception to the calling class? Answer: In your catch statement, rethrow the exception. Question: What will happen in the application after the ArgumentException in the in the example is thrown? Answer: If this code is within a try block, execution will jump to the catch block to handle the exception. If this code is not in a try block, then the GetCourse method would exit, and execution would jump to the exception handling of the caller.

Exceptions
Question: What possible things can we do to better handle the exception? Answer: We could record the error within a log file or database for analysis by administrators. We could also attempt to resolve the issue, if possible. Question: Should we use an event (such as DataErrorFixed) or should we use an exception to notify the caller that the value of UnitPriceDiscount was invalid, and has been changed to a valid value? Answer: Using an event handler would incur less overhead, and provide a notification to any event listener that the value has changed. Since the invalid value is easily rectified, there is little value in raising an exception. Unhandled exceptions will also be passed to the user interface. Using an exception will also incur the overhead of creating an exception object, which can be expensive when creating performance code. Question: What is the benefit to creating custom exception classes?

6-22

Introduction to Object-Oriented Programming with Microsoft Visual Studio 2008

Answer: By using a custom exception class, code that catches the exception can better respond to a specific exception type. The custom exception class can more easily implement code within the exception class, such as logging exception information.

Delegates, Events and Exceptions

6-23

Detailed Demo Steps


Demonstration: Exceptions Detailed demonstration steps
Create a custom exception handler class
1. 2. Log on to 6367A-LON-SVR1 as Administrator using the password Pa$$w0rd. Using Microsoft Visual Studio 2008 open the solution located at: Visual C#: E:\Demos\Mod06\Starter\CS\ExceptionsDemo\ExceptionsDemo.sln Visual Basic: E:\Demos\Mod06\Starter\VB\ExceptionsDemo\ExceptionsDemo.sln Build the project. Open Form1.cs (Visual C#) or Form1.vb (Visual Basic) from the Solution Explorer. Examine the form. In the Orders.cs (Visual C#) or Orders.vb (Visual Basic) file, add a custom exception class named OrderException, that is derived from System.Exception. Override the parameterized constructor that accepts a single string parameter. Name the string parameter message. Within the method, call the base constructor passing OrderException: concatenated to message.

3. 4. 5. 6.

Add code to throw the custom exception


1. At the top of the RaisePricingChanged() method within the OrderItem class, add code that checks the following error conditions and throws a new OrderException with an appropriate message. a. b. c. LineTotal cannot be less than 0. UnitPriceDiscount cannot be less than 0 or greater than 1. UnitPrice cannot be less than 0.

Add code to handle the custom exception


1. 2. 3. 4. 5. 6. In Form1.cs (Visual C#) or Form1.vb (Visual Basic) within the button1_click method, add a try/catch block that catches an exception of type OrderException named ex. Within the try block, add order.OrderItems[0].UnitPriceDiscount = 1.2; (Visual C#) or order.OrderItems(0).UnitPriceDiscount=1.2 (Visual Basic). Within the catch block, add code that displays a friendly message followed by the exception within a message box. Add a breakpoint to the button1_Click method. Run the project. Step through the code and examine how the exception object is created and thrown, and then handled.

6-24

Introduction to Object-Oriented Programming with Microsoft Visual Studio 2008

Add an event handler to handle error notification


Note: This portion of the demonstration illustrates that not all classes use exceptions to pass error information. 1. 2. Open Form1.cs (Visual C#) or Form1.vb (Visual Basic), and then add a default event handler for the orderItemDataGridView.DataErrror event. Within the orderItemDataGridView_DataError method, add code that displays a friendly error message followed by the exception. You can find the exception object as a property of the DataGridViewDataErrorEventArgs object. Run the project. Change the UnitPriceDiscount to 1.2. Show the resulting MessageBox. Notice how the datagrid raises an event handler and passes the exception. Note: Event handlers can also be used to notify for business logic errors. Although the Exception object is passed within DataGridViewDataErrorEventArgs, custom event handlers are not required to pass the exception object. Also recall that event handlers can use a multicast event handler, thereby notifying multiple handlers as well as possibly avoiding the additional object creation that exceptions incur.

3. 4.

Modify the Orders class to protect the encapsulated data


1. 2. 3. Click OK. Notice how the application still stores the UnitPriceDiscount and calculates the new price. Also notice how exceptions and event handlers can be ignored by the calling code. Stop the program execution and open Orders.cs (Visual C#) or Orders.vb (Visual Basic) from the Solution Explorer. Within Orders.cs (Visual C#) or Orders.vb (Visual Basic) in the OrderItem class, examine the code for the UnitPriceDiscount property. Notice how the property allows for any valid integer to be stored. Replace the code within the set accessor to: a. b. c. Set the _unitPriceDiscount to 0 if the value is less than 0. Set the _unitPriceDiscount to 1 if the value is greater than 1. Otherwise, set the _unitPriceDiscount to the value.

4.

Note: Notice how the code restricts the UnitPriceDiscount from being set to anything over 1 (100%).

5. 6.

Run the project. Change the value of the UnitPriceDiscount to 1.2. Notice the effect of the change.

Delegates, Events and Exceptions

6-25

Additional Reading
Handling Exceptions

try-catch (C# Reference) try-finally (C# Reference) TryCatchFinally Statement (Visual Basic)

Creating Custom Exceptions

Exception Class

Throwing Exceptions

Creating and Throwing Exceptions (C# Programming Guide) How to: Throw an Exception in Visual Basic Exception.InnerException Property

6-26

Introduction to Object-Oriented Programming with Microsoft Visual Studio 2008

Module Reviews and Takeaways


Review questions
1. How do you handle an event raised by an instance of a class? Answer: You create an event handler method with the same signature as the event, and associate it with the event it is going to handle. 2. How do you associate an event with an event handler method? Answer: Use the += (Visual C#) or AddHandler (Visual Basic). You can also declare the instance using WithEvents, and use the Handles clause in Visual Basic to associate an event with an event handler. 3. How can you find out the error message associated with an exception. Answer: In your catch statement, associate the event with a variable name, and then access the message property of the exception.

Common issues related to delegates, events, and exceptions


Identify the causes for the following common issues related to delegates, events, and exceptions, and fill in the troubleshooting tips. For answers, refer to relevant lessons in the module. Issue You have created a BankAccount class. The class contains a Withdraw method that raises an Overdrawn event when the account is overdrawn. You run the application, but no error message appears to the user when the account is overdrawn. Using the debugger, you step through your code and you see the statement that raises the event execute successfully. What could be wrong? You implement exception handling in your code using try catch finally. A Select command issued to the database fails, but no error message displays to the user. Using the debugger, you see your class execute the Catch statement to handle and log the error. However, when the control returns to the form class, the code continues normal execution and does not go to the catch statement. What should you do to ensure the catch statement in the form is executed? Troubleshooting tip

There may not be an event handler method defined for the event, or you may have created an event handler method and not associated it with the event.

Rethrow the exception within the catch section in your class, or throw a new exception within the catch section in your class. When you handle an exception, the exception is not passed up to the calling class.

Real-world issues and scenarios


1. You have a BankAccount class with a BillPayment method. The BillPayment method calls an UpdateBalance method in the BankAccountDB Class. When the account number does not exist, no exception is raised by the database, and the command to update the balance just updates zero records. You want to know when the account number did not exist. How can you modify the BankAccountDB class to let you know when the account number does not exist?

Delegates, Events and Exceptions

6-27

Answer: Write code in the UpdateBalance method to check how many records were updated by the Update statement sent to the database. If zero records are updated, throw a new exception UnknownAccount, and let the BillPayment method in the BankAccount class handle the exception. 2. You have a BankAccount class with a Withdraw method. Users are allowed to overdraw from their accounts by up to five hundred dollars, however whenever an account is overdrawn you want to notify the user that their account is overdrawn and let them know by how much their account is overdrawn. How can you implement this in your code? Answer: In the BankAccount class, define an event called Overdrawn with a parameter AmountOverdrawn. In the Withdraw method, if the amount withdrawn exceeds the account balance, raise the AmountOverdrawn event and pass the amount overdrawn. In your user interface class, create an event handler method to display a message to the user when the event is raised.

Best practices related to delegates, events, and exceptions


Supplement or modify the following best practices for your own work situations: Handle all events before control returns to the user, or the application will terminate. Validate business rules and values specified in fields before executing processing to avoid the overhead of throwing exceptions during processing. Use events to communicate across instances of classes.

6-28

Introduction to Object-Oriented Programming with Microsoft Visual Studio 2008

Lab Review Questions and Answers


Lab 6A
1. Could more than one search method be called by the search form? Answer: Yes, the search form uses a delegate to register more than one search method. 2. What is the difference between a delegate and an event? Answer: Delegates offer more flexibility than events, and therefore additional planning and complexity are required to implement them. Events follow a standardized approach and offer a consistent notification model that other developers understand more quickly. 3. What other events could be created for the OrderItem class? Answer: Answers will vary. OrderItems could have events for: When the quantity changes (to notify any inventory management systems that maybe handling events). When the product status changes from in-stock to backordered.

Lab 6B
1. Could the exception within the lab be handled in a better way? Answer: Yes, the error could have been logged. Sending raw exception messages to the user interface is never good practice. If corrective action could have been applied, it should have. However, the example in the lab allows for little corrective action to be taken. 2. What is the benefit of handling an exception with a custom exception class? Answer: By using a custom exception class, code can be added later to the exception class to implement a custom logging solution. As well, having a custom exception class to be thrown helps to identify the type of error within the catch, which allows for more specific corrective action to be taken during the catch. 3. What is the difference between using an event as a notification model versus using an exception? Answer: Using an event can offer a multicast notification model, whereas exceptions cannot. Exceptions usually incur more overhead because of the additional exception object creation. Exceptions are the expected method of handling errors and follow a standardized approach, which helps with code consistency.

Designing Object Collaboration

7-1

Module 7
Designing Object Collaboration
Contents:
Lesson 1: Introduction to Class Interactions Lesson 2: Adding Interactions to a Design Lesson 3: Evaluating the Design Lesson 4: Introduction to Patterns Module Reviews and Takeaways Lab Review Questions and Answers 2 4 9 12 15 17

7-2

Introduction to Object-Oriented Programming with Microsoft Visual Studio 2008

Lesson 1

Introduction to Class Interactions


Contents:
Question and Answers 3

Designing Object Collaboration

7-3

Question and Answers


Design Goals for Interactions
Question: Is a design that simply works the best solution? Answer: No. I can hammer a nail in with my shoe, and it works, but there are better ways to do it. Question: Are there other considerations that would influence design? Answer: Yes. Meeting specific requirements such as legal compliance may influence the design choices and make one solution more ideal than another.

Comparing Methods of Interaction


Question: What is the advantage of using an event instead of using a delegate, if events are fundamentally based on the delegate model? Answer: Delegates allow for complete customization of the registration and invocation process, whereas events follow a more standardized approach of registration and invocation.

Defining Interaction Boundaries


Question: When defining a Web service or assembly, what can you use to define the functionality exposed across the boundary? Answer: After you have defined the interactions, you can define an interface for the methods that are exposed across the boundary.

Discussion: Creating a Sequence Diagram


Question: Should we show all of the possibilities that may occur in a scenario in a sequence diagram? Answer: No. It is more important that each diagram be clear and show one specific scenario. Activity diagrams are better at showing all the different scenarios that can occur. If it is important to show each variation, then you should create a sequence diagram for each scenario.

7-4

Introduction to Object-Oriented Programming with Microsoft Visual Studio 2008

Lesson 2

Adding Interactions to a Design


Contents:
Question and Answers Additional Reading 5 8

Designing Object Collaboration

7-5

Question and Answers


Discussion: Adding Methods to a Design
Question: Should SendEmail send individual parameters or an object? Answer: In this case we do not have an object that contains the text of the e-mail, so we send the individual parameters. You could define a new class called EmailParameters, which has properties specifically designed to hold the parameters required to send an e-mail, and pass that instead. Question: Why is the Mailer class created? Answer: The responsibility of sending an e-mail does not fit with the responsibilities of any other classes. The mailer class will be responsible for knowing how to connect to the mail server, and send an e-mail. Question: What would you do if you needed to include the course price and course name in the email? Answer: The course price and course name are properties of the course class. You would either need to instantiate the course class using the courseid stored in the SessionRegister Sessions property, or you could modify the Session class to store the course type instead of courseid, so that all the course properties are available through the SessionRegister Sessions property.

Adding Events to a Design


Question: Would you ever raise the same event from two different methods? Answer: Yes, it is possible for the same event to occur under different conditions. Imagine an AccountOverdrawn event, which could be raised from a TransferFunds method, a Withdraw method or a BillPayment method. Question: Which event might you want to raise? Answer: Minimum Number of Students Reached. Question: Which class will know when that event occurs? Answer: The Session class, which contains a collection of all registrations for a session and the MinimumToRun property. Question: Which method should raise the event? Answer: The AddRegistration method will know when the minimum number of registrations has been reached. Question: Which class should handle the event? Answer: SessionRegister, because it knows how to send an e-mail to the student.

7-6

Introduction to Object-Oriented Programming with Microsoft Visual Studio 2008

Discussion: Adding Events to a Design


Question: Are there other event handlers that could be added to the MinReached event? Answer: Answers will vary based on business requirements, but one possible scenario is you could add an event handler that notifies the operations manager that the minimum number of students has been reached so they can begin to plan the logistics required to run the course such as ensuring equipment and books will be in place.

Adding Delegates to a Design


Question: What is the advantage of using delegates over events? Answer: Events are based on the delegate model. However, delegates allow for complete control over the registration/deregistration process, and you can control which class is responsible for each stage of the process of instantiating and invoking a delegate.

Discussion: Adding Delegates to a Design


Question: Where is the opportunity to use a delegate? Answer: Sometimes you need to print a copy of the confirmation, sometimes you need to e-mail the confirmation. You can create a delegate that could point to either a sendEmail or a PrintConfirmation method. Question: Where would you place the code that calls the delegate? Answer: The SessionRegister class would invoke the delegate when a registration ID is returned within the Register method. Question: Where would you instantiate the delegate? Answer: Answers will vary, but when the student logs on, their preferences could be checked. If they have chosen preference of e-mail, the delegate is instantiated to point to a SendEmail method. If they chose printed letter, the delegate is instantiated to point to a PrintLetter method. Question: Could you have solved this without a delegate? Answer: Yes, you could simply write an If statement after the registration is confirmed that determines whether to call the SendEmail method of the Mailer class, or the PrintLetter method of the Printer class. The benefit of using the delegate is that the code is not aware of the class it is calling. If a bulk mailing company is hired to print out letters, a new class could be added that interfaces with their application and accepts the details for letters to be printed, and only the code that instantiates the delegate would need to be updated.

Discussion: Adding Exceptions to a Design


Question: What error condition do you need to handle? Answer: The session may be full.

Designing Object Collaboration

7-7

Question: What method will detect the exception? Answer: The AddRegistration method of the Session class, because it knows the maximum number of registrations, and has the registrations collection of all registrations for the session. Question: Which class should handle the exception? Answer: Answers will vary, but the user interface must receive the exception, because the user interface will need to display a message to the user, informing them the session is full. Question: Why does the RegisterSession rethrow the SessionFull exception? Answer: Because we want the student who is using the application to know that the session is full. By rethrowing the exception, we allow the user interface class to know that an exception has occurred and display an error message to the user.

7-8

Introduction to Object-Oriented Programming with Microsoft Visual Studio 2008

Additional Reading
Adding Events to a Design

Event Design

Designing Object Collaboration

7-9

Lesson 3

Evaluating the Design


Contents:
Question and Answers 10

7-10

Introduction to Object-Oriented Programming with Microsoft Visual Studio 2008

Question and Answers


Validation Techniques
Question: Are there other techniques you can use to evaluate your class interaction design? Answer: Answers will vary based on student experience.

Discussion: Evaluating the Interaction Design


Question: Does each class still have a single responsibility? Answer: Answers may vary. However, the SessionRegister class appears to be defining the message body format and sending it as a string in the content parameter to the Printer or Mailer class. It is not the responsibility of the SessionRegister class to format a message for an e-mail or printing. The SessionRegister class should only know what registration information to include in the e-mail text. Consider changing content to an XML parameter that contains elements that must be included in the output, and perhaps including a messageType parameter so the Mailer or Printer class knows what elements are in the XML parameter. Also consider leaving the formatting of the message body to the Printer or Mailer class. This might be a better solution. Question: Has the best communication model been chosen for each interaction? (Method, Event, Delegate, Exception) Answer: Answers will vary. However, an event could be raised when a registration is complete that passes the registration information. The SendConfirmation delegate could be registered as the event handler for the RegistrationComplete event. The advantage to using an event is you could add additional event handlers to react to the RegistrationComplete event, such as a method that determines how many course kits to order, or a method that processes payment. Question: Are there any all powerful classes within the design? Answer: Answers will vary. The SessionRegister class is starting to become a bit big, and may eventually be broken up into two smaller classes. The final decision will depend on the other scenarios that are handled by the application, and the other classes and methods that are defined based on those scenarios. Question: Are there any classes that do too little? Answer: Answers will vary. The registration class in this sequence diagram does very little. It is used to retrieve a registration ID for a session registration. This functionality could be included in the session class. However, there are other scenarios that use the registration class, which may add additional functionality. So it is not possible to make the decision as to whether to remove the registration class by looking at a single sequence diagram. Question: Have we reduced dependencies within each communication? Answer: Answers will vary, there are several class interactions that pass individual class properties. If one of these properties such as sessionId changed type from integer to string, the method signatures

Designing Object Collaboration

7-11

would change and other classes would be affected. However we are not passing a large number of properties so there are minimal dependencies between the classes.

7-12

Introduction to Object-Oriented Programming with Microsoft Visual Studio 2008

Lesson 4

Introduction to Patterns
Contents:
Question and Answers Additional Reading 13 14

Designing Object Collaboration

7-13

Question and Answers


Defining Patterns
Question: Have you ever reused a pattern from a previous application in a new application? Answer: Answers will vary based on experience.

Discussion: Evaluating a Pattern


Question: What is the problem/challenge the pattern helps solve? Answer: It helps you avoid performing expensive instantiation by cloning an object to create an object, instead of instantiating an object to create a new one. Question: Does the problem/challenge exist in the solution? Answer: You have four classes that are slow to instantiate, but implementing the prototype pattern only helps when you are making multiple instances of an object. You are unlikely to create two instances of the CourseCatalog or SessionRegister classes in the application. However, you will have multiple instances of the Session object, so you may want to consider implementing the prototype pattern for the Session class. Question: What advantages/disadvantages are there with implementing a particular pattern? Answer: You must implement the ICloneable interface on the Session class. This will require implementing a Clone method, which makes an exact copy of a Session object. Copying the CourseId, StartDate, MaxNbrStudents, and MinimumToRun properties will be straightforward, but copying the Registrations property which contains a collection of Registration objects, will be more difficult to code.

7-14

Introduction to Object-Oriented Programming with Microsoft Visual Studio 2008

Additional Reading
Defining Patterns

Using Patterns to Define a Software Solution patterns & practices

Common Patterns

Exploring the Factory Design Pattern Exploring the Singleton Design Pattern Design Patterns Model View Presenter Model View Controller

Designing Object Collaboration

7-15

Module Reviews and Takeaways


Review questions
1. Which type of class interactions support two-way communication between classes? Answer: Methods, and delegates. 2. Which type of class interactions support asynchronous communication between classes? Answer: Events are asynchronous, and delegates can be invoked asynchronously if the BeginInvoke method is used to invoke the delegate. 3. You are trying to design a solution, and you are having trouble deciding what methods to include in the user interface. Which category of design patterns should you research for possible design patterns to help you design your solution? Answer: Model View design patterns, which are design patterns for splitting user interface responsibilities from business responsibilities.

Common issues related to designing object collaboration


Identify the causes for the following common issues related to designing object collaboration, and fill in the troubleshooting tips. For answers, refer to relevant lessons in the module. Issue You raise an event to indicate that a student does not have the prerequisites for a course. The event should set the message body to include a message indicating the prerequisites are not met, yet the message body included in the email to the student does not always contain the extra text to indicate the prerequisites are not met. You step through the code, and the event is raised successfully and the event handler that sets the message text is firing. Why is the message text in the e-mail sometimes missing the prerequisite message text? You write a method call from one object to another to pass information about a scheduled session. You pass in the session startdate, the session ID, and the session start date. During development, you discover you also need to pass in the instructor contact information. You are concerned that you may discover additional session properties that need to be passed later in design, and you do not want to change the method signature again. How should you handle this problem? Troubleshooting tip

Events are asynchronous. They fire event handlers, but you do not control when the event handlers fire. If your code continues execution and performs an action such as sending an e-mail, there is no guarantee that the event handler will have finished execution before your code sends the e-mail. For this situation, events are not a good choice for the class interaction, because we cannot guarantee the event handler has sent the message text before the e-mail is sent.

Pass a session object as a parameter, instead of passing parameters for individual session properties. That way, all the session properties are available to the method.

7-16

Introduction to Object-Oriented Programming with Microsoft Visual Studio 2008

Real-world issues and scenarios


1. You write a method that performs a calculation to determine the profit that will be made from running a particular session. During initial design, the number of registrations was the only parameter passed to the method. Later in design, the user asked to include the course duration and course price as parameters to the method. The user has suggested they may identify other parameters to pass later, which may be required to calculate the profit for a session. Is there a way to design the method call so that even if new parameters need to be added, the signature of the method does not change? Solution: You could create a class called ProfitCalculatorParameters, and pass a single parameter to the method of that class type. Create properties in the class for each parameter that needs to be passed to the method. When the method is called, an instance of the ProfitCalculatorParameters class is created, and each property is set. The ProfitCalculatorParameters object is passed to the method. Within the method, the properties can be accessed to retrieve the information required to perform the calculation. If additional values must be passed later to perform the calculation, you just add the extra properties to the class, but you do not need to change the method signature. 2. You have several class interactions. A user clicks a button on a form class, which calls an UpdateOrder method, which calls a ExecuteUpdateStatement method, which connects to the database and executes a SQL statement to update an Order record in the database. Sometimes the database connection cannot be opened, and the Open method of the database connection object throws an exception. You want to make sure the UpdateOrder method and the form class are aware of the exception, but you still want to include exception handling in your ExecuteUpdateStatement method, which will log the exception details to an error log so the maintenance team can investigate the exception. How can you handle the exception in the ExecuteUpdateStatement and still pass the exception information to the calling methods? Solution: You add a try catch to the ExecuteUpdateStatement method to handle the exception thrown when the Open method of the database connection object throws an exception. In the Catch statement, you write the code to log the exception in the error log file, and then you rethrow the exception so it is passed up to the calling method.

Best practices related to designing object collaboration


Supplement or modify the following best practices for your own work situations: Use exceptions for inter-object interactions that indicate an error has occurred. Use events for asynchronous communication that may require multiple event handlers. Reuse design patterns in your own designs instead of reinventing solutions on your own. When you are researching design patterns, focus on learning what problems are solved by what patterns. When you find a design pattern that solves a problem you are facing, take the time to sit down and evaluate that pattern to determine if you should implement it in your own solution.

Tools
Tool Office Visio Use for Drawing sequence diagrams Where to find it

http://office.microsoft.com/enus/visio/default.aspx

Designing Object Collaboration

7-17

Lab Review Questions and Answers


1. What did you find was the most challenging part of developing the design? Answer: Answers will vary. 2. Sequence diagrams can often become large and complicated. What could be done to keep sequence diagrams clear and concise? Answer: The goal of a sequence diagram is to tell a single story. If a diagram has too much detail or too many steps in it, it may be better to break down the sequence diagram into smaller, simpler diagrams. A sequence diagram should also limit the number of choices within the diagram. For example, consider a diagram with a YES/NO choice. If the selection is YES, then one execution path gets followed.I If the selection is NO, then we follow a very different execution path. The question that needs to be asked is, Is the diagram clear? If having the YES/NO choice in the diagram complicates the diagram too much, then it may be better to show a sequence diagram that shows only the YES execution path, and another sequence diagram with only the NO execution path. 3. What did you find was the most challenging part of determining if a particular design pattern would be beneficial to your design? Answer: Answers will vary. 4. Could you add more than one design pattern to a design? Answer: Yes. 5. Within Exercise 4, a pattern was selected and provided to you. How does your knowledge about different design patterns affect which patterns you might select to evaluate? Answer: Knowing and understanding various patterns becomes a benefit to the developer by increasing their understanding of different design approaches. A developer that knows and understands more design patterns will have the benefit of being able to apply the appropriate design pattern to the appropriate solution.

Deploying Components and Class Libraries

8-1

Module 8
Deploying Components and Class Libraries
Contents:
Lesson 1: Introduction to Components and Class Libraries Lesson 2: Deploying a Component/Class Library Lesson 3: Best Practices for Deploying a Component/Class Library Module Reviews and Takeaways Lab Review Questions and Answers 2 5 8 16 19

8-2

Introduction to Object-Oriented Programming with Microsoft Visual Studio 2008

Lesson 1

Introduction to Components and Class Libraries


Contents:
Question and Answers Additional Reading 3 4

Deploying Components and Class Libraries

8-3

Question and Answers


Upgrading and Maintenance within the Software Development Lifecycle
Question: Why is it helpful to have the ability to have multiple versions of the same assembly in production? Answer: Because you can add functionality and deploy a new version of the assembly for one application while allowing the other applications to continue using the older, unchanged assembly version. Question: Should you leave the other applications running on the old versions of the assembly? Answer: Ideally, you should go back and upgrade the other applications to work on the new version when you have the opportunity. If you have multiple versions of an assembly running in production, it can be very difficult to maintain when changes are required, because you can lose track of which changes are in which version, and which application is running which version. Question: Have you ever had to update shared code? Did you have to update multiple applications to deal with the change? Answer: Answers will vary based on experience.

Discussion: Identifying Components and Class Libraries in a Business Scenario


Question: Which classes should be kept in the same assembly? Answer: Answers will vary, but the following is one possible solution. The Aircraft class will be in an assembly by itself, because it is shared across applications. The ticket class will be in an assembly by itself, because it requires FileIOPermissions. The Flight class, Domestic Flight Class, and International Flight Class will be in the same assembly. You could put the Crew class, Air Crew class, and Ground Crew class in the same assembly as the Flight classes, since you will access all these classes whenever you assign crew to a flight. The Passenger and Frequent Flyer class will be in the same assembly.

8-4

Introduction to Object-Oriented Programming with Microsoft Visual Studio 2008

Additional Reading
Factors for Creating Deployable Units of Software

Requesting Permissions Permissions View Tool (Permview.exe)

Software Development Lifecycle

MSF Process Model Overview

Deploying Components and Class Libraries

8-5

Lesson 2

Deploying a Component/Class Library


Contents:
Question and Answers Detailed Demo Steps Additional Reading 6 7 12

8-6

Introduction to Object-Oriented Programming with Microsoft Visual Studio 2008

Question and Answers


Preparing an Application to Use Component/Class Libraries
Question: Why should you import the namespace of the referenced assembly? Answer: Then you will not need to modify your code to include the fully qualified name for all of the classes in the class library.

Deploying an Assembly
Question: When should you deploy to the /bin directory instead of the global assembly cache? Answer: When the assembly is only used by a single application. However, there are advantages to storing an assembly in the global assembly cache even if it is only used by a single application. You will learn the benefits of using the global assembly cache in the next topic.

What Is the Global Assembly Cache?


Question: What are the benefits to deploying to the global assembly cache? Answer: Two applications can share the same assembly, you can have two versions of the assembly in production at the same time, it will load faster because it is the first place the application checks for the assembly, and because verification was done when it was loaded in the global assembly cache. Finally, when two applications use the same assembly it is only loaded in memory once. Question: Can you have two versions of an assembly in the global assembly cache? Answer: Yes, the global assembly cache allows you to have multiple versions of the same assembly available at the same time. This allows you to have different applications running different versions of the same assembly.

Deploying Components and Class Libraries

8-7

Detailed Demo Steps


Demonstration: Creating and Referencing a Class Library from an Application Detailed demonstration steps
1. Start Visual Studio 2008. Load one of the following solutions based on the language in which you would like to complete the demonstration: 2. 3. 4. Microsoft Visual Basic: E:\Demos\Mod08\Starter\VB\Module08Demo.sln Microsoft Visual C#: E:\Demos\Mod08\Starter\CS\Module08Demo.sln

Open Form1 in the code view, and review the code for the Upper function and the btnOk_Click method. Press the F5 key to run the application. Type aaa into the text box, and then click OK. You should see a message box with AAA returned. Add a new project of type Class Library. Ensure you are using the same language as the current application. Enter MyUtils in the name box, leave the location as is, and then click OK. Rename Class1.cs or Class1.vb to Utils.cs or Utils.vb. Create a public function called Upper that is similar to the one in Form1, but add to it code that will display assembly information, such as the assembly name and version, and whether the assembly is in the global assembly cache or not. Your code should resemble the following:

5.

[Visual Basic]
Public Function Upper(ByVal str As String) As String Dim Asm As System.Reflection.Assembly = _ System.Reflection.Assembly.GetExecutingAssembly Return str.ToUpper() & " From GAC : " _ & Asm.GlobalAssemblyCache.ToString() & ", Name " & Asm.FullName End Function

[Visual C#]
public string Upper(string str) { System.Reflection.Assembly Asm = System.Reflection.Assembly.GetExecutingAssembly(); return str.ToUpper() + " From GAC : " + Asm.GlobalAssemblyCache.ToString() + ", Name " + Asm.FullName; }

6. 7.

In the Module08Demo project, add a reference to the MyUtils project. Return to the code in Form1. Delete or comment out the local Upper function, and modify the code in the click event to use the Upper method in the class library. Your code should resemble the following:

[Visual Basic]
Dim AUtil As New MyUtils.Utils MessageBox.Show(AUtil.Upper(txtString.Text))

8-8

Introduction to Object-Oriented Programming with Microsoft Visual Studio 2008

[Visual C#]
MyUtils.Utils AUtils = new MyUtils.Utils(); MessageBox.Show(AUtils.Upper(txtString.Text));

8.

Save the projects, and build the solution. Make sure the build is successful, and then press F5 to execute the application. Type aaa into the text box, and then click OK. You should see a message box the result. Note that the assembly is not in the global assembly cache. Stop the project execution.

9.

Deploying Components and Class Libraries

8-9

Detailed Demo Steps


Demonstration: Installing an Assembly into the Global Assembly Cache Detailed demonstration steps
1. Start Visual Studio 2008. Load one of the following solutions based on the language in which you would like to complete the demonstration: 2. 3. 4. 5. Visual Basic: E:\Demos\Mod08\Starter\VB\Module08Demo.sln Visual C#: E:\Demos\Mod08\Starter\CS\Module08Demo.sln

Select the MyUtils project, right-click the project, and then select Properties. Once the Properties window opens, select the Signing tab. Sign the assembly by creating a key file with the name of MyUtils. Secure the file with a password of Pa$$w0rd. Ensure the build configuration is set to release, and build the project. Several methods exist to add an assembly to the global assembly cache. You are going to use a setup project. Add a new project of type Setup. In the Name box, change the name to MyUtils Setup. Ensure the setup project is selected, and on the right-click the File System on Target Computer node. Click Add Special Folder, and then click Global Assembly Cache Folder. Once the global assembly cache folder has been created, right-click on the folder, and then click Add, and then click Assembly. Select the Browse tab, and then browse to the Release folder of the MyUtils project. Select the MyUtils.dll file, and then click OK. Save and build the setup project. Ensure the build is successful. Right-click the MyUtils Setup project, and select Install. Follow the prompts of the installation wizard, and click next on each screen to install the assembly. Once the installation is successful, ensure Module08Demo is set as the startup project, and then press F5 to run the application. Type aaa into the text box, and then click OK. The message displayed will now have the value of true to indicate the assembly in being run from the global assembly cache. Stop the execution of the project.

6.

7.

8.

9.

10. Click Start, point to Administrative Tools, then open the Microsoft .NET Framework 2.0 Configuration tool. Click Manage the Assembly Cache, and then click View List of Assemblies in the Assembly Cache. Find the MyUtils assembly. Right-click the assembly, and select Properties. View the Properties of the Assembly. Click Cancel to close the window.

8-10

Introduction to Object-Oriented Programming with Microsoft Visual Studio 2008

Detailed Demo Steps


Demonstration: Updating and Deploying a Class Library/Component Detailed demonstration steps
1. Start Visual Studio 2008. Load one of the following solutions based on the language in which you would like to complete the demonstration: 2. Visual Basic: E:\Demos\Mod08\Starter\VB\Module08Demo.sln Visual C#: E:\Demos\Mod08\Starter\CS\Module08Demo.sln

Make a minor change to the code in the assembly by following the steps: a. b. Open the Utils class in the MyUtils Project in the code view. In the line that returns the value, modify the code so that three exclamation marks are added to the string.

3.

Right-click the MyUtils project, and then select Properties. Click the Application tab, and then click the Assembly Information button. Change the Assembly and File version to 2.0.0.0, and then click OK. Close the property pages. Build the MyUtils project, and ensure that the build is successful. Press F5 to execute the project, type aaa into the text box, and then click OK. The message box displayed does not have the exclamation marks, and it indicates that it is loaded from the global assembly cache. You are going to now add a second version of the assembly to the GAC using the Microsoft .NET Framework 2.0 configuration tool. a. b. Open the Microsoft .NET Framework 2.0 Configuration tool, click Manage the Assembly Cache, and then Add an assembly to the Assembly Cache. Navigate to the release folder of the MyUtils project. Select the MyUtils.dll file, and then click Open. You should now have two versions of the assembly in the cache (version 1.0.0.0. and 2.0.0.0).

4.

5.

6. 7.

Return to Visual Studio 2008 and press F5 to execute the application. Type aaa into the text box, and then click OK. You should see a message indicating that the assembly was loaded from the global assembly cache, is version 2.0.0.0, and should have exclamation marks at the end of the message. However, you would like the application to continue using version 1.0.0.0 of the assembly. To achieve this, you need to add a binding redirection instruction in an app.config file. a. b. Right-click Module08Demo, select Add, and then click New Item. Select Application Configuration File, and the click Add. Once the app.config file has been added and loaded, type the following XML into the configuration file just above the bottom </configuration> tag:

8.

Deploying Components and Class Libraries

8-11

<runtime> <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1"> <dependentAssembly> <assemblyIdentity name="MyUtils" publicKeyToken="" culture="neutral" /> <!-- Assembly versions can be redirected in application, publisher policy, or machine configuration files. Redirection from younger to older version in our case --> <bindingRedirect oldVersion="2.0.0.0" newVersion="1.0.0.0" /> </dependentAssembly> </assemblyBinding> </runtime>

9.

Open the Microsoft .NET Framework 2.0 configuration tool. Click Manage the Assembly Cache, and then click View List of Assemblies in the Assembly Cache.

10. Find the MyUtils assembly. Since the public key is the same for version 1.0.0.0 and 2.0.0.0, either version of the MyUtils assembly can be used. Right-click the assembly, and then select Properties. Copy the Public Key Token value, and then click Cancel. 11. Return to Visual Studio 2008, and paste the Public key token value in the app.config file as the value for publicKeyToken. Note that in your example you are rerouting the request from a new assembly version to an older assembly version. Save the app.config file. 12. Build Module08Demo and ensure the build is successful. 13. Press F5 to start the execution of the application. Type aaa into the text box, and then click OK. You should see a message that displays version 1.0.0.0 of the assembly. 14. Stop the program execution.

8-12

Introduction to Object-Oriented Programming with Microsoft Visual Studio 2008

Additional Reading
What Is an Assembly?

Manifest Generation and Editing Tool (Mage.exe)

Deploying an Assembly

Deploying Assemblies

What Is the Global Assembly Cache?

Global Assembly Cache

Installing an Assembly into the Global Assembly Cache



How to: Install an Assembly into the Global Assembly Cache Global Assembly Cache Tool (Gacutil.exe) Assembly Cache Viewer (Shfusion.dll)

Manage Versioning within an Application Using a Component/Class Library



Redirecting Assembly Versions How to: Create a Publisher Policy Strong Name Tool (Sn.exe)

Deploying Components and Class Libraries

8-13

Lesson 3

Best Practices for Deploying a Component/Class Library


Contents:
Question and Answers Additional Reading 14 15

8-14

Introduction to Object-Oriented Programming with Microsoft Visual Studio 2008

Question and Answers


Best Practices: Deploying Components/Class Libraries
Question: Have you ever made a change to code and deployed it, only to cause an error in production because you discovered after the fact that the code was used somewhere else? Answer: Answers vary based on student experience.

Verifying Results
Question: What issues have you encountered in the past when deploying updates? Answer: Answers will vary based on experience, but a common issue is updating code that is shared, deploying it, and accidentally causing errors in the application that shares the assembly.

Deploying Components and Class Libraries

8-15

Additional Reading
Best Practices: Deploying Components/Class Libraries

Understanding Service-Oriented Architecture

8-16

Introduction to Object-Oriented Programming with Microsoft Visual Studio 2008

Module Reviews and Takeaways


Review questions
1. How do you redirect an application to use a different version of an assembly in the Global Application Cache? Answer: Use a publisher policy file to redirect a binding request to a newer instance of the component. Next, use the Assembly Generation tool (Al.exe) to compile this XML file into a publisher policy assembly. Finally, deploy the publisher policy assembly with the new version of the component. 2. What sort of changes in a class are most likely to affect other assemblies? Answer: Changes to method signatures. This include changing a method name, adding new parameters, removing parameters, changing return types, or changing the type of a parameter. 3. Why is it important to specify the permissions required for an assembly within a class library? Answer: So the administrator is aware of the permissions required by the assembly, and can grant the necessary permissions. If you do not specify the permissions, the administrator may not grant the permissions, and the assembly may generate exceptions at runtime due to insufficient permissions.

Additional reading

How to: Create a Publisher Policy

Common issues related to deploying components and class libraries


Identify the causes for the following common issues related to deploying components and class libraries, and fill in the troubleshooting tips. For answers, refer to relevant lessons in the module. Issue You deploy a new version of an assembly into the global assembly cache, but your application does not appear to pick up the changes in your new assembly. What is the most likely cause? You have an application which reads information from an XML file. You have tested the application thoroughly in development. When you deploy the application to production, the application works as expected, but when you execute the code that reads from the file, you receive an error message informing you that you do not have sufficient permissions to read the file. What is the most likely cause? You have an application which reads information from an XML file. You have tested the application thoroughly in Troubleshooting tip The application will continue to run with the version of the assembly with which it was compiled. If you are only modifying and deploying the assembly, you must redirect the application to the new version of the assembly using a publisher policy file.

The assembly containing the class that reads the file requires the FileIOPermission, and that permission has not been granted to the assembly. If you do not specify the permissions required for the assembly, the assembly will execute, but an exception will be raised if you attempt to perform an operation for which you have not been granted the necessary permissions.

Your assembly has requested the FileIOPermission as a minimum permission to ensure it will be able to read the XML file, but the assembly does not have the minimum

Deploying Components and Class Libraries

8-17

development. When you deploy the application to production, the application works as expected, but when you try to execute any code in the assembly that reads the file, you receive an error message informing you that you do not have the required minimum permissions. What is the most likely cause?

permissions. When you specify the minimum permissions required in an assembly, the .NET Framework will verify the assembly has the necessary permissions when it is loaded. You will not be able to access any functionality in the assembly until the minimum permissions have been granted to the assembly. This check helps you catch missing permissions without retesting your entire application.

Real-world issues and scenarios


1. You are deploying a small Windows application that is used by your department to help with tracking project issues. You have separated the classes from the user interface by creating a class library. The functionality in the classes is very specific your project issue tracking application. When you deploy the class library assembly, should you deploy it to the application directory, or the global assembly cache? Answer: In this scenario, there is little benefit to putting the code into the global assembly cache. It is not shared, and it does not require the fastest possible performance. You can deploy the assembly to the application directory. Deploying to the application directory is the simplest solution. 2. You have completed building and testing an object-oriented application. You are trying to decide how to divide up your classes into different class libraries. What are some of the factors you should consider when dividing up the classes? Answer: Which classes may be reused by another application? Which classes are used together to perform a task in the application? Which classes require extra security permissions?

Best practices related to deploying components and class libraries


Supplement or modify the following best practices for your own work situations: Install shared assemblies in the Global Application Cache. Design interfaces and method signatures to be as reusable as possible. Document the dependencies between assemblies so that you are aware of the full risk, impact, and testing involved in making a change.

Tools
Tool Use for Where to find it .NET Framework 2.0 Software Development Kit .NET Framework 2.0 Software Development Kit .NET Framework 2.0 Software Development Kit

GacUtil.exe

Installing strong-named assemblies to the global assembly cache Global assembly cache viewer that allows you to view and add assemblies in the global assembly cache A MMC Snap-in that allows you to manage and configure assemblies in the global assembly cache.

Assembly Cache Viewer (shfusion.dll) .NET Framework Configuration Tool (Mscorcfg.msc)

8-18

Introduction to Object-Oriented Programming with Microsoft Visual Studio 2008

Assembly Linker (Al.exe)

Generates a file with an assembly manifest, used to build a publisher policy assembly file to redirect an assembly for an application

.NET Framework 2.0 Software Development Kit

Deploying Components and Class Libraries

8-19

Lab Review Questions and Answers


1. Why is it important to ensure that the structure of the application in terms of components is decided early? Answer: Creating new class libraries and refactoring code late in a project can be a lot of work, and can lead to errors. 2. What was necessary to do to the assemblies, before building the setup package for deployment? Answer: Sign the assemblies. 3. What can be used to redirect the binding of an assembly? Answer: A configuration file with a rebinding declaration can be used.

Introduction to Object-Oriented Programming with Microsoft Visual Studio 2008

R-1

Resources
Contents:
Microsoft Learning Technet and MSDN Content Communities 2 3 6

R-2

Introduction to Object-Oriented Programming with Microsoft Visual Studio 2008

Microsoft Learning
This section describes various Microsoft Learning programs and offerings. Microsoft Learning You can search for the skills assessment options available through Microsoft, also 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

Introduction to Object-Oriented Programming with Microsoft Visual Studio 2008

R-3

Technet and MSDN Content


There is no content from Technet in this course.

MSDN
Structures and Classes Extending Metadata Using Attributes Auto-Implemented Properties (C# Programming Guide) Using Properties (C# Programming Guide) Adding Properties to Your Class Event Design Patterns & practices Visual Studio 2005 Class Designer Object Browser Test Bench Drill Into .NET Framework Internals to See How the CLR Creates Runtime Objects Project Templates in Visual Studio Web Application Projects Overview Comparing Web Site Projects and Web Application Projects Value Types in the Common Type System NET Type Fundamentals System.Collections.Generic Namespace IConvertible Interface Casting and Type Conversions (C# Programming Guide) How to: Convert a string to an int (C# Programming Guide) Converting Types XML Documentation Comments (C# Programming Guide) What's new in Visual Studio 2008 Intellisense Features XML Comments Let You Build Documentation Directly From Your Visual Studio .NET Source Files (C#) Visual Basic Language Concepts Documenting Your Code with XML (Visual Basic) Garbage Collection: Automatic Memory Management in the Microsoft .Net Framework Garbage Collection Operator Overloading Usage Guidelines

R-4

Introduction to Object-Oriented Programming with Microsoft Visual Studio 2008

Operator Overloading Tutorial Inheritance (C# Programming Guide) Inheritance Basics (Visual Basic Programming Guide) Abstract MustInherit Base First statement of this Sub New must be a call to MyBase.New or MyClass.New (More Than One Accessible Constructor Without Parameters) Hiding through Inheritance Override Modifiers (Visual Basic Programming Guide) abstract (C# Reference) override (C# Reference) Interfaces (C# Programming Guide) Interface Statement (Visual Basic Programming Guide) Interfaces in Visual Basic (Visual Basic Programming Guide) IDisposable Interface Garbage Collection: Automatic Memory Management in the Microsoft .NET Framework Implements Statement (Visual Basic Programming Guide) How to: Explicitly Implement Interface Members (C# Programming Guide) Inheritance and Interfaces Qualifying .NET Types for Interoperation Visual Studio 2005 Class Designer UML Notation Microsoft Office Visio 2007 Product Overview The Nordic Object-Relational Design (an ORM example) Delegates (C#) Delegates in Visual Basic Using Delegates (C# Programming Guide) A Primer on Creating Type-Safe References to Methods in Visual Basic .NET How to: Declare, Instantiate and Use a Delegate (C# Programming Guide) Delegates and the AddressOf Operator (Visual Basic Programming Guide) Asynchronous Programming Using Delegates Asynchronous Programming Overview EventHandler Delegate

Introduction to Object-Oriented Programming with Microsoft Visual Studio 2008

R-5

WithEvents and the Handles Clause (Visual Basic Programming Guide) Events Tutorial (C# Programmer&#8217;s Reference) How to: Add Events to a Class (Visual Basic Programming Guide) Raising an Event How to: Connect Event Handler Methods to Events AddHandler and RemoveHandler try-catch (C# Reference) try-finally (C# Reference) TryCatchFinally Statement(Visual Basic) Exception Class Creating and Throwing Exceptions (C# Programming Guide) How to: Throw an Exception (Visual Basic Application Development) Exception.InnerException Property Using Patterns to Define a Software Solution Exploring the Factory Design Pattern Exploring the Singleton Design Pattern Design Patterns Model View Presenter Model View Controller Requesting Permissions Permissions View Tool MSF Process Model Overview Manifest Generation and Editing Tool (Mage.exe) Deploying Assemblies Global Assembly Cache How to: Install an Assembly Into the Global Assembly Cache Global Assembly Cache Tool (Gacutil.exe) Assembly Cache Viewer (Shfusion.dll) Redirecting Assembly Versions How to: Create a Publisher Policy Strong Name Tool Understanding Service-Oriented Architecture

R-6

Introduction to Object-Oriented Programming with Microsoft Visual Studio 2008

Communities
There is no content from Communities in this course.

Introduction to Object-Oriented Programming with Microsoft Visual Studio 2008

R-7

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: Document or CD part number Page number or location 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.

Das könnte Ihnen auch gefallen