Sei sulla pagina 1di 232

OFFICIAL

MICROSOFT

L EARNING

10266A

PRODUCT

OFFICIAL MICROSOFT L EARNING 10266A PRODUCT Programming in C# with Microsoft© Visual Studio© 2010 Companion Content

Programming in C# with Microsoft© Visual Studio© 2010

Companion Content

Information in this document, including URL and other Internet Web site references, is subject to change without notice. Unless otherwise noted, the example companies, organizations, products, domain names, e-mail addresses, logos, people, places, and events depicted herein are fictitious, and no association with any real company, organization, product, domain name, e-mail address, logo, person, place or event is intended or should be inferred. Complying with all applicable copyright laws is the responsibility of the user. Without limiting the rights under copyright, no part of this document may be reproduced, stored in or introduced into a retrieval system, or transmitted in any form or by any means (electronic, mechanical, photocopying, recording, or otherwise), or for any purpose, without the express written permission of Microsoft Corporation.

Microsoft may have patents, patent applications, trademarks, copyrights, or other intellectual property rights covering subject matter in this document. Except as expressly provided in any written license agreement from Microsoft, the furnishing of this document does not give you any license to these patents, trademarks, copyrights, or other intellectual property.

The names of manufacturers, products, or URLs are provided for informational purposes only and Microsoft makes no representations and warranties, either expressed, implied, or statutory, regarding these manufacturers or the use of the products with any Microsoft technologies. The inclusion of a manufacturer or product does not imply endorsement of Microsoft of the manufacturer or product. Links may be provided to third party sites. Such sites are not under the control of Microsoft and Microsoft is not responsible for the contents of any linked site or any link contained in a linked site, or any changes or updates to such sites. Microsoft is not responsible for webcasting or any other form of transmission received from any linked site. Microsoft is providing these links to you only as a convenience, and the inclusion of any link does not imply endorsement of Microsoft of the site or the products contained therein.

© 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 of their respective owners.

Product Number: 10266A

Released: 09/2010

Introducing C# and the .NET Framework

1-1

Module 1

Introducing C# and the .NET Framework

Contents:

Lesson 1: Introduction to the .NET Framework 4

2

Lesson 2: Creating Projects Within Visual Studio 2010

5

Lesson 3: Writing a C# Application

9

Lesson 4: Building a Graphical Application

12

Lesson 5: Documenting an Application

17

Lesson 6: Debugging Applications by Using Visual Studio 2010

20

Module Review and Takeaways

22

Lab Review Questions and Answers

24

1-2

Programming in C# with Microsoft© Visual Studio© 2010

Lesson 1

Introduction to the .NET Framework 4

Contents:

Question and Answers

3

Additional Reading

4

Introducing C# and the .NET Framework

1-3

Question and Answers

What Is the .NET Framework 4?

Question: What is the purpose of the .NET Framework 4, and the three main components that it provides?

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

The Purpose of Visual C#

Question: Which programming languages have you used?

Answer: Ask students which languages they have used.

What Is an Assembly?

Question: Why would you choose to distribute an assembly rather than distribute the source code?

Answer: An assembly is a compiled unit that can contain multiple functional components that is ready to run. If you distributed raw source files, end users would have to compile the code before they could run the application.

How the Common Language Runtime Loads, Compiles, and Runs Assemblies

Question: What steps does the CLR perform when you run your application?

Answer: The CLR performs the following steps:

1. The Class Loader locates and loads all assemblies that the application requires.

2. The assemblies will already be compiled into MSIL. The MSIL-to-native compiler verifies the MSIL code and then compiles all assemblies into machine code ready for execution.

3. The Code Manager loads the executable assembly and runs the Main method.

What Tools Does the .NET Framework Provide?

Question: You have created two applications that both use an assembly called Contoso.ReportGenerator.dll. Both applications will run on the same machine. What is the best approach to share the Contoso.ReportGenerator.dll assembly and which tool would you use?

Answer: You would install the assembly into the Global Assembly Cache (GAC) by using the Gacutil.exe tool.

1-4

Programming in C# with Microsoft© Visual Studio© 2010

Additional Reading

What Is the .NET Framework 4?

For more information about the .NET Framework, see the Microsoft .NET page at

The Purpose of Visual C#

For more information about the Microsoft implementation of Visual C# 2010, see the Visual C# page http://go.microsoft.com/fwlink/?LinkId=192877.

For more information about the new features of C# 4.0, see the What's New in Visual C# 2010 page at http://go.microsoft.com/fwlink/?LinkId=192878.

What Is an Assembly?

For more information about the purpose and features of assemblies, see the Assemblies in the Common Language Runtime page at http://go.microsoft.com/fwlink/?LinkId=192879.

For more information about assembly versioning, see the Assembly Versioning page at

For more information about assembly signing, see the SignTool.exe (Sign Tool) page at

What Tools Does the .NET Framework Provide?

For more information about the tools that the .NET Framework provides, see the .NET Framework Tools page at http://go.microsoft.com/fwlink/?LinkId=192882.

Introducing C# and the .NET Framework

1-5

Lesson 2

Creating Projects Within Visual Studio 2010

Contents:

Question and Answers

6

Detailed Demo Steps

8

1-6

Programming in C# with Microsoft© Visual Studio© 2010

Question and Answers

Key Features of Visual Studio 2010

Question: What are the main reasons why you may choose Visual Studio 2010 over a text editor such as Notepad++?

Answer: Answers should include:

The intuitive IDE in Visual Studio 2010.

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

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

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

Templates in Visual Studio 2010

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

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

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

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

Answer: Possible answers include:

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

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

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

The Structure of Visual Studio Projects and Solutions

Question: What role does the .sln file play in Visual Studio solutions?

Answer: .NET solutions act as a wrapper for solution settings and your .NET

also enable you to build multiple projects without having to open multiple instances of Visual Studio.

projects.

.NET solutions

Creating a .NET Framework Application

Question: What is the purpose of code snippets?

Answer: Code snippets remove the need for developers to repeatedly type common code constructs.

Building and Running a .NET Framework Application

Question: Describe two ways to build and run a .NET Framework application.

Introducing C# and the .NET Framework

1-7

Answer: You can build a .NET application by using Visual Studio or csc.exe on the command line.

Demonstration: Disassembling a .NET Framework Assembly

Question: When developing a .NET Framework application, how would you find Ildasm useful?

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

1-8

Programming in C# with Microsoft© Visual Studio© 2010

Detailed Demo Steps

Demonstration: Disassembling a .NET Framework Assembly Demonstration Steps

Task 1: Run an existing .NET application

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

2. In Windows Explorer, move to the E:\Demofiles\Mod1\Demo1 folder, and then double-click MyFirstApplication.exe.

3. In the MyFirstApplication window, point out:

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

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

That the Command Prompt window does not automatically close until you click the X icon on the toolbar.

4. Close the MyFirstApplication window.

Task 2: Open Ildasm

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

2. In Windows Explorer, move to the C:\Program Files\Microsoft SDKs\Windows\v7.0A\bin folder, and then double-click ildasm.exe.

Task 3: Disassemble an existing .NET Framework assembly

1. In the Il Dasm window, on the File menu, click Open.

2. In the Open dialog box, move to the E:\Demofiles\Mod1\Demo1 folder, and then double-click MyFirstApplication.exe.

Introducing C# and the .NET Framework

1-9

Lesson 3

Writing a C# Application

Contents:

Question and Answers

10

Additional Reading

11

1-10

Programming in C# with Microsoft© Visual Studio© 2010

Question and Answers

What Are Classes and Namespaces?

Question: In your console application, you want to use the Console class, which is part of the System namespace. How do you bring the System namespace into scope?

Answer: You could use the using statement to bring the System namespace into scope.

The Structure of a Console Application

Question: In your console application, you have a method called Main. What is the purpose of the Main method?

Answer: The Main method provides an entry point into the console application.

Performing Input and Output by Using a Console Application

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

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

Capture the key that the user pressed.

Answer: The correct answer is:

Console.WriteLine("Please press any key“);

ConsoleKeyInfo keyPressed = Console.ReadKey();

Best Practices for Commenting C# Applications

Question: Why is it important for you to comment your code?

Answer: Answers should include:

To improve the readability of your code.

To capture the rationale behind your logic.

To explain the purpose of elements in your code.

Introducing C# and the .NET Framework

1-11

Additional Reading

The Structure of a Console Application

For more information about command-line arguments, see the Main() and Command-Line Arguments (C# Programming Guide) page at http://go.microsoft.com/fwlink/?LinkId=192889.

Performing Input and Output by Using a Console Application

For more information about the Console class, see the Console Class page at

1-12

Programming in C# with Microsoft© Visual Studio© 2010

Lesson 4

Building a Graphical Application

Contents:

Question and Answers

13

Detailed Demo Steps

15

Additional Reading

16

Introducing C# and the .NET Framework

1-13

Question and Answers

What Is WPF?

Question: Why would you choose to use WPF to create an application instead of Windows Forms?

Answer: WPF enables you to create applications with much more compelling user interfaces, and offers greater control over user interface components.

The Structure of a WPF Application

Question: Can you think of any other markup languages that behave in a similar way to XAML?

Answer: Web applications that use HTML.

The WPF Control Library

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

Answer: Answers could include:

For layout, use a Grid control.

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

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

For a Submit button, use a Button control.

WPF Events

Question: When you develop your WPF applications, what two ways can you use to specify events for controls?

Answer: Declaratively by using XAML markup, or imperatively in Visual C# code.

Building a Simple WPF Application

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

Answer: Answers should include:

Solution Explorer

Properties

XAML

Design

Code Editor

1-14

Programming in C# with Microsoft© Visual Studio© 2010

Demonstration: Building a Simple WPF Application

Question: When developing a .NET Framework application, how would you find Ildasm useful?

Answer: You can set properties by using the Properties window, or by editing the XAML for the control directly by using the XAML window.

Introducing C# and the .NET Framework

1-15

Detailed Demo Steps

Demonstration: Building a Simple WPF Application Demonstration Steps

Task 1: Create a new WPF application

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

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

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

a. In the center pane, click WPF Application.

b. In the Name box, type MyFirstWpfApp

c. In the Location box, type E:\Demofiles\Mod1\Demo2\Starter

Task 2: Add controls to the WPF application

1. On the View menu, click Toolbox.

2. In the Toolbox window, double-click Button.

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

Task 3: Set the properties for the controls

1. In the Design window, click the Button control.

2. In the Properties window, set the Button property to ClickMeButton.

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

FontSize: 20

Height: 50

Width: 150

4. In the XAML window, perform the following:

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

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

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

1-16

Programming in C# with Microsoft© Visual Studio© 2010

Additional Reading

What Is WPF?

For more information about what WPF is, see the Introduction to WPF page at

The WPF Control Library

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

WPF Events

For more information about how WPF handles events, see the Events (WPF) page at

Introducing C# and the .NET Framework

1-17

Lesson 5

Documenting an Application

Contents:

Question and Answers

18

Additional Reading

19

1-18

Programming in C# with Microsoft© Visual Studio© 2010

Question and Answers

What Are XML Comments?

Question: Why would you use XML comments rather than standard comments?

Answer: XML comments enable you to define comments in a more structured way. You can extract XML by using tools such as Sandcastle Help File Builder.

Common XML Comment Tags

Question: Which tag would you use to provide a detailed description of a method?

Answer: The <remarks> tag.

Generating Documentation from XML Comments

Question: Which switch do you need to provide to get csc.exe to produce XML output?

Answer: The /doc switch.

Introducing C# and the .NET Framework

1-19

Additional Reading

What Are XML Comments?

For more information about XML comments, see the XML Documentation Comments (C# Programming Guide) page at http://go.microsoft.com/fwlink/?LinkId=192887.

Common XML Comment Tags

For more information about XML comment tags, see the Recommended Tags for Documentation Comments (C# Programming Guide) page at http://go.microsoft.com/fwlink/?LinkId=192888.

Generating Documentation from XML Comments

For more information about Sandcastle Help File Builder, see the Sandcastle Help File Builder page at http://www.codeplex.com/SHFB.

1-20

Programming in C# with Microsoft© Visual Studio© 2010

Lesson 6

Debugging Applications by Using Visual Studio 2010

Contents:

Question and Answers

21

Introducing C# and the .NET Framework

1-21

Question and Answers

Debugging in Visual Studio 2010

Question: What are some of the debug functions that Visual Studio 2010 provides?

Answer: Answers should include:

Start/stop debugging.

Halt on a breakpoint.

Using Breakpoints

Question: How would you use the debug functions in Visual Studio 2010 to debug your application and pause on a specific line of code?

Answer: Answers should include:

1. Locate the line of interest and set a breakpoint.

2. Start the application with debugging.

Stepping Through and Over Code

Question: Why would you use the Step into and Step over debug functions?

Answer: Answers should include:

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

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

Using the Debug Windows

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

Answer: Answers should include:

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

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

1-22

Programming in C# with Microsoft© Visual Studio© 2010

Module Review and Takeaways

Review Questions

1. What is the purpose of the .NET Framework and the role of Visual C#?

Answer: The .NET Framework 4 provides a comprehensive development platform that offers a fast and efficient way to build applications and services. C# is the language of choice for many developers. It uses a very similar syntax to C, C++, and Java, with several extensions and features designed for operation with the .NET Framework.

2. What is the purpose of Visual Studio 2010 templates?

Answer: Visual Studio 2010 supports the development of different types of applications such as Windows-based client applications, Web-based applications, services, and libraries. To help you get started, Visual Studio 2010 provides several application templates that provide a structure for the different types of applications.

3. What is the purpose of Visual Studio projects and solutions?

Answer: A project is used to organize source files, references, and project-level configuration settings that make up a single .NET Framework application or library. A single Visual Studio solution is a container for one or more projects.

4. What is the purpose of a Main method?

Answer: Every .NET Framework application that compiles into an executable file must have a Main method. This method provides the CLR with an entry point into the application. When you run a .NET Framework application, the Main method is the first method that the CLR executes.

5. List some of the controls that WPF provides.

Answer: Any of Button, Canvas, ComboBox, Grid, Label, StackPanel, and TextBox.

6. What is the purpose of XML comments?

Answer: In Visual Studio 2010, you can add comments to your source code that will be processed to an XML file. This file can then be the input to a process that creates Help documentation for the classes in your code.

7. What is the purpose of the Visual Studio 2010 debugger?

Answer: Debugging is an essential part of application development. You may notice errors as you write code, but some errors—especially logic errors—may only occur in specific circumstances that you do not test for. Users may report these errors to you, and you will have to correct them. Visual Studio 2010 provides several tools to help you debug code.

Best Practices Related to Writing a C# Application

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

Keep the Main method small and lightweight.

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

Define controls by using meaningful names and avoid reference to the underlying control type, for example, labelName.

Add comments to your code that describe your thought process.

Introducing C# and the .NET Framework

1-23

Tools

Tool

Use for

Where to find it

Caspol.exe

Enables users to modify the machine, user, and enterprise security policy. This can include defining a custom permission set and adding assemblies to the full trust list.

C:\Windows\Microsoft.NET\Frame

 

work\v4.0.30319

 

Gacutil.exe

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

C:\Program Files\Microsoft

 

SDKs\Windows\v7.0A\bin

 

Ildasm.exe

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

C:\Program Files\Microsoft

 

SDKs\Windows\v7.0A\bin

 

Makecert.exe

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

C:\Program Files\Microsoft

 

SDKs\Windows\v7.0A\bin

 

Ngen.exe

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

C:\Windows\Microsoft.NET\Frame

 

work\v4.0.30319

 

Sn.exe

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

C:\Program Files\Microsoft

 

SDKs\Windows\v7.0A\bin

 

1-24

Programming in C# with Microsoft© Visual Studio© 2010

Lab Review Questions and Answers

1. What methods did you use to capture and display information in your console application? Answer: The static ReadLine and WriteLine methods.

2. What event did you handle on the Format Data button in your WPF application? Answer: The Click event handler.

3. What debugging functions did you use when you verified the application? Answer: Start Debugging, breakpoint, Step into, Step over, and the Immediate window.

4. How do you instruct Visual Studio 2010 to produce an XML file that contains XML comments? Answer: Set the XML documentation file property.

Using C# Programming Constructs

2-1

Module 2

Using C# Programming Constructs

Contents:

Lesson 1: Declaring Variables and Assigning Values

2

Lesson 2: Using Expressions and Operators

5

Lesson 3: Creating and Using Arrays

8

Lesson 4: Using Decision Statements

11

Lesson 5: Using Iteration Statements

14

Module Review and Takeaways

16

Lab Review Questions and Answers

17

2-2

Programming in C# with Microsoft© Visual Studio© 2010

Lesson 1

Declaring Variables and Assigning Values

Contents:

Question and Answers

3

Additional Reading

4

Using C# Programming Constructs

2-3

Question and Answers

What Are Variables?

Question: What is a variable and how are variables used in Microsoft® .NET Framework applications?

Answer: Variables store values that the application requires in temporary memory locations. Applications process these values to perform functions such as calculations, data analysis, and database interactions.

What Are Data Types?

Question: What type would you use to store a sequence of alphanumeric characters?

Answer: A String type.

Declaring and Assigning Variables

Question: What is the syntax for declaring and assigning a variable?

Answer: One possible answer is DataType variableName = Value;.

What Is Variable Scope?

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

Answer: Use class scope and declare a private field at the class level. Use class scope and declare a private field at the class level.

Converting a Value to a Different Data Type

Question: You are converting a string to an int type, but you are unsure whether the string will contain a valid int value. Which conversion approach should you use?

Answer: You should use the int.TryParse method.

Read-Only Variables and Constants

Question: What are the main differences between a constant and a read-only variable?

Answer: Answers should include the following:

The declaration keyword, const and readonly.

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

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

2-4

Programming in C# with Microsoft© Visual Studio© 2010

Additional Reading

Declaring and Assigning Variables

For more information about the keyword in C#, see the C# Keywords page at

For more information about naming conventions, see the General Naming Conventions page at

For more information about capitalization conventions, see the Capitalization Conventions page at

What Is Variable Scope?

For more information about scopes, see the 3.7 Scopes page at

Converting a Value to a Different Data Type

For more information about the System.Convert class, see the Convert Class page at

Read-Only Variables and Constants

For more information about constants, see the const (C# Reference) page at

Using C# Programming Constructs

2-5

Lesson 2

Using Expressions and Operators

Contents:

Question and Answers

6

Additional Reading

7

2-6

Programming in C# with Microsoft© Visual Studio© 2010

Question and Answers

What Is an Expression?

Question: What is the value of the expression "99" + "1"?

Answer: The string, “991”.

What Are Operators?

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

Answer: The % operator.

Specifying Operator Precedence

Question: How can you control the order of processing in an expression?

Answer: Use parentheses to override the precedence of operators. Expressions in the parentheses are evaluated first.

Best Practices for Performing String Concatenation

Question: Why is concatenating strings considered bad practice, and how can you avoid it?

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

Using C# Programming Constructs

2-7

Additional Reading

What Are Operators?

For more information about the operator in C#, see the C# Operators page at http://go.microsoft.com/fwlink/?LinkId=192896, and the Operators (C# Programming Guide) page at

Best Practices for Performing String Concatenation

For more information about the StringBuilder class, see the StringBuilder Class page at

2-8

Programming in C# with Microsoft© Visual Studio© 2010

Lesson 3

Creating and Using Arrays

Contents:

Question and Answers

9

Additional Reading

10

Using C# Programming Constructs

2-9

Question and Answers

What Is an Array?

Question: What is an array, and why would you want to use arrays in a C# application?

Answer: An array is a set of elements that are grouped together and managed as a unit. Arrays enable you to handle a set of closely related data.

Creating and Initializing Arrays

Question: How do you declare a multidimensional array?

Answer: Answers should resemble the following code example.

Type[ , ] arrayName = new Type[ Size1, Size2 ];

Common Properties and Methods Exposed by Arrays

Question: What members would you use to locate the last element in an array, and then change that element’s value?

Answer: Use the following code example to illustrate the answer.

int[] oldNumbers = { 1, 2, 3, 4, 5 }; oldNumbers.SetValue(5000, oldNumbers.Length -1);

Accessing Data in an Array

Question: Explain two approaches to accessing data in an array.

Answer: Answers should include two of the following:

Indexer

GetValue()

Explicit GetEnumerator()

Implicit GetEnumerator()

2-10

Programming in C# with Microsoft© Visual Studio© 2010

Additional Reading

Creating and Initializing Arrays

For more information about arrays, see the Multidimensional Arrays section on the Harness the Features of C# to Power Your Scientific Computing Projects page at

For more information about single-dimensional arrays, see the Single-Dimensional Arrays (C# Programming Guide) page at http://go.microsoft.com/fwlink/?LinkId=192900.

For more information about multidimensional arrays, see the Multidimensional Arrays (C# Programming Guide) page at http://go.microsoft.com/fwlink/?LinkId=192901.

For more information about jagged arrays, see the Jagged Arrays (C# Programming Guide) page at

Common Properties and Methods Exposed by Arrays

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

Using C# Programming Constructs

2-11

Lesson 4

Using Decision Statements

Contents:

Question and Answers

12

Additional Reading

13

2-12

Programming in C# with Microsoft© Visual Studio© 2010

Question and Answers

Using One-Way If Statements

Question: When must you enclose the code in the body of an if statement in braces?

Answer: You must enclose the code in the body of an if statement in braces if you want to perform more than one statement. It is also good practice even if you only use a single statement because you may need to add additional statements later.

Using Either-Or If Statements

Question: Think of a scenario where you may want to use the if else statement and discuss.

Answer: This question is designed to stimulate discussion among the students, so there is no definitive answer. However, one possible answer could be to prompt a user for input and test whether the input is valid. If it is valid, process the input; if it is invalid, display an error message.

Using Multiple-Outcome If Statements

Question: What is the purpose of the else statement in an else if construct?

Answer: The else statement is the default block and should contain logic that will be executed if none of the conditions in the previous if and else if conditions return false.

Using the Switch Statement

Question: With the exception of the default case, is the order of the cases in a switch statement important?

Answer: No. You cannot fall through from one case to another, so the order in which they occur is immaterial.

Guidelines for Choosing a Decision Construct

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

Answer: The switch statement.

Using C# Programming Constructs

2-13

Additional Reading

Using Either-Or If Statements

For more information about the ?: operator, see the ?: Operator (C# Reference) page at

2-14

Programming in C# with Microsoft© Visual Studio© 2010

Lesson 5

Using Iteration Statements

Contents:

Question and Answers

15

Using C# Programming Constructs

2-15

Question and Answers

Types of Iteration Statements

Question: Which iteration statement would you use to prompt a user for a valid response?

Answer: The most suitable loop for this scenario is the do loop, although there are many alternative solutions. Get students to justify their answers.

Using the While Statement

Question: When using the while loop, what type must the condition expression evaluate to?

Answer: The [condition] can be any expression that evaluates to a Boolean value.

Using the Do Statement

Question: What is the minimum number of iterations that a do loop will perform?

Answer: One, because the condition is evaluated at the end of the loop.

Using the For Statement

Question: What are the four components of a for loop?

Answer: Answers should include the following:

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

A starting value for the counter variable.

A limit for the counter variable.

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

Break and Continue Statements

Question: What is the difference between the break and continue statements?

Answer: The break statement enables you to exit the loop entirely, and skip to the next line of code outside the loop. The continue statement is similar to the break statement except that, instead of exiting the loop entirely, you simply skip the remaining code in the current iteration, test the condition, and then start the next iteration of the loop.

2-16

Programming in C# with Microsoft© Visual Studio© 2010

Module Review and Takeaways

Review Questions

1. If you declare a variable with the type var, what does it mean?

Answer: It means that it is an implicit variable where the data type is inferred by the initializer’s value.

2. How can you control the order of processing in an expression?

Answer: You can use parentheses to control the order of processing in an expression.

3. What is the purpose of arrays?

Answer: An array is a set of objects that are grouped together and managed as a unit.

4. Name an alternative approach to using the if else statements.

Answer: Using either the switch statement or the ?: operator.

5. Which loop construct should you use to execute a block of code one or more times?

Answer: The do loop.

Best Practices Related to Using C# Constructs

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

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

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

When you access elements in an array by using the index of an element, make sure that you test to see whether the index exists. If the index doesn’t exist, you will get an IndexOutOfRange exception.

Avoid too many nested if else and loop statements because they can make debugging your applications complicated.

Avoid using break and continue statements in loops unless you really need them.

Using C# Programming Constructs

2-17

Lab Review Questions and Answers

1. Which .NET Framework class and method did you use to calculate the square root?

Answer: The Math class and the Sqrt method.

2. Which .NET Framework class did you use to construct the string that represented the binary number, and what benefits does this class provide?

Answer: The StringBuilder class, which enables you to dynamically build a string without the overhead of concatenating several string variables.

3. Which loop construct did you use to iterate through all of the rows in the matrix1 array, and why was it a good choice?

Answer: I used the for loop. This was a good choice because I knew how many rows were in the array.

Declaring and Calling Methods

3-1

Module 3

Declaring and Calling Methods

Contents:

Lesson 1: Defining and Invoking Methods

2

Lesson 2: Specifying Optional Parameters and Output Parameters

9

Module Review and Takeaways

12

Lab Review Questions and Answers

13

3-2

Programming in C# with Microsoft© Visual Studio© 2010

Lesson 1

Defining and Invoking Methods

Contents:

Question and Answers

3

Detailed Demo Steps

5

Additional Reading

8

Declaring and Calling Methods

3-3

Question and Answers

What Is a Method?

Question: Why do you need to use methods when developing a .NET Framework application with C#?

Answer: All code must belong to a method. If you don’t define methods, you cannot implement behavior. In addition, all C# programs must have at least one method called Main, which defines the starting point for the application.

Creating a Method

Question: What are the four elements in the method specification?

Answer: The four elements are:

Access modifier

Return type

Method name

Parameter list

Calling a Method

Question: How can you call the method in the following code example?

void DeleteReport(string reportName)

Answer: Answers should resemble the following code example. Users should specify the method name and a string parameter, and there is no return value.

DeleteReport("MyReport");

Creating and Calling Overloaded Methods

Question: What is meant by overloading a method?

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

Using Parameter Arrays

Question: How do you define a method that takes a parameter array?

Answer: You need to do the following:

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

You must prefix the parameter with the params keyword.

The parameter must be an array.

3-4

Programming in C# with Microsoft© Visual Studio© 2010

Refactoring Code into a Method

Question: Why would you want to refactor code into a method?

Answer: When you need to perform the same logic several times in different places.

Testing a Method

Question: Why would you want to use unit tests when developing your .NET Framework applications?

Answer: Unit tests provide an excellent way to help simplify the testing process and ensure that your tests are reliable and easily repeatable.

Demonstration: Refactoring and Testing a Method

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

Answer: Answers can include:

In the Test View window.

In the Test Results window.

On the Test menu.

Declaring and Calling Methods

3-5

Detailed Demo Steps

Demonstration: Refactoring and Testing a Method Demonstration Steps

Task 1: Open the existing application and view the existing code

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

2. In Visual Studio 2010, on the File menu, click Open, and then click Project/Solution.

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

4. In Solution Explorer, in the MethodRefactorAndTestDemo.sln project, right-click the Program.cs file, and then click View Code.

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

Minimum number for any of the random numbers.

Maximum number for any of the random numbers.

Number of random numbers required.

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

Task 2: Refactor an existing code block

1. In the Code Editor window, in the Main method, select the code in the following code example.

int[] randomNumbers = new int[numberOfRequirednumbers]; Random numberGenerator = new Random();

for (int count = 0; count < numberOfRequirednumbers; count++)

{

randomNumbers[count] = numberGenerator.Next(min, max);

}

2. Right-click the selected code block, point to Refactor, and then click Extract Method.

3. In the Extract Method dialog box, perform the following, and then click OK:

a. In the New method name box, type GenerateRandomNumbers

b. In the Preview method signature box, show students the proposed signature for the method (the int[] return type, and three int parameters).

4. Show students the new GenerateRandomNumbers method, and the GenerateRandomNumbers method call.

Task 3: Generate a unit test for the GenerateRandomNumbers method

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

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

3-6

Programming in C# with Microsoft© Visual Studio© 2010

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

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

3. In the New Test Project dialog box, click Create.

4. In the Add InternalsVisibleTo Attribute dialog box, click Yes.

Task 4: Examine the auto-generated unit test method

1. In the Code Editor window, in the ProgramTests class, navigate to the GenerateRandomNumbersTest method.

2. Show students the following:

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

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

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

Task 5: Modify the auto-generated unit test method

1. Make the following changes to the GenerateRandomNumbersTest method:

Set the max variable to 100.

Set the numberOfRequirednumbers variable to 999.

Remove the int[] expected = null; // TODO: Initialize to an appropriate value line.

Replace the Assert.AreEqual(expected, actual); line with Assert.AreEqual(1000, actual.Length);

Remove the Assert.Inconclusive("Verify the correctness of this test method."); line.

Your code should resemble the following code example.

public void enerateRandomNumbersTest()

{

int min = 0; // TODO: Initialize to an appropriate value int max = 100; // TODO: Initialize to an appropriate value int numberOfRequirednumbers =999; // TODO: Initialize to an appropriate value int[] actual; actual = Program_Accessor.GenerateRandomNumbers(min, max, numberOfRequirednumbers); Assert.AreEqual(1000, actual.Length);

}

2. On the Build menu, click Build Solution.

Task 6: Run the unit test

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

Declaring and Calling Methods

3-7

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

Failed GenerateRandomNumbersTest TestProject1 Assert.AreEqual failed. Expected:<1000>. Actual:<999>.

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

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

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

3-8

Programming in C# with Microsoft© Visual Studio© 2010

Additional Reading

Creating a Method

For more information about methods, see the Methods (C# Programming Guide) page at

Creating and Calling Overloaded Methods

For more information about method overloading, see the Member Overloading page at

Using Parameter Arrays

For more information about parameter arrays, see the params (C# Reference) page at

Refactoring Code into a Method

For more information about refactoring in C#, see the Refactoring (C#) page at

Declaring and Calling Methods

3-9

Lesson 2

Specifying Optional Parameters and Output Parameters

Contents:

Question and Answers

10

Additional Reading

11

3-10

Programming in C# with Microsoft© Visual Studio© 2010

Question and Answers

What Are Optional Parameters?

Question: When defining a method with optional parameters, in what order must you specify the parameters?

Answer: You must specify all mandatory parameters before optional parameters.

Calling a Method by Using Named Arguments

Question: What is the syntax for using named parameters in method calls?

Answer: methodName(parameterName1 : value1, parameterName2 : value2);

What Are Output Parameters?

Question: What happens if you attempt to call MyMethod with the code in the following code example?

MyMethod(10, 101.1F, 20);

Answer: Your code will not compile. You must provide an argument that can hold a value, such as a variable, and you must specify the out keyword.

Declaring and Calling Methods

3-11

Additional Reading

What Are Optional Parameters?

For more information about optional parameters, see the Named and Optional Arguments (C# Programming Guide) page at http://go.microsoft.com/fwlink/?LinkId=192909.

What Are Output Parameters?

For more information about output parameters, see the out parameter modifier (C# Reference) page at

3-12

Programming in C# with Microsoft© Visual Studio© 2010

Module Review and Takeaways

Review Questions

1. What return type do you specify for a method that does not return any data?

Answer: void

2. What term is given to the process of defining multiple methods with the same name, but different parameter lists?

Answer: Method overloading.

3. What is the difference between an optional parameter and a named argument?

Answer: An optional parameter is part of a method signature, and specifies that a parameter has a default value. When an application invokes the method, it can omit the argument that corresponds to this parameter and the method will use the default value instead.

A named argument is the syntax that an application can use when it invokes a method. An application can specify the arguments in any order by prefixing them with the name of the parameter that they should be used for.

4. What is the purpose of output parameters?

Answer: Output parameters enable you to return multiple values from a method.

Best Practices Related to Using Methods

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

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

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

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

Declaring and Calling Methods

3-13

Lab Review Questions and Answers

1. When using output parameters in a method, what must you do before the method completes?

Answer: You must assign a value to the parameter, otherwise the code will not compile.

2. When adding optional parameters to an existing method signature, why will your code run successfully without making changes to any of the existing method calls?

Answer: When you add optional parameters, you provide default values. If you do not explicitly set the optional parameters in your method calls, the default parameters will be used.

3. When creating a unit test method in a Visual Studio test project, what attribute must you decorate your test method with?

Answer: The TestMethod attribute.

Handling Exceptions

4-1

Module 4

Handling Exceptions

Contents:

Lesson 1: Handling Exceptions

2

Lesson 2: Raising Exceptions

8

Module Review and Takeaways

10

Lab Review Questions and Answers

11

4-2

Programming in C# with Microsoft© Visual Studio© 2010

Lesson 1

Handling Exceptions

Contents:

Question and Answers

3

Detailed Demo Steps

5

Additional Reading

7

Handling Exceptions

4-3

Question and Answers

What Is an Exception?

Question: Discuss your experiences of applications that have crashed with other students and the instructor.

Answer: This question is designed to stimulate discussion among the students, so there is no definitive answer. Students should think about all of the applications that they have used that have behaved unexpectedly or crashed. You can then point out that the developer failed to handle such conditions.

Using a Try/Catch Block

Question: How would you use the try/catch block to catch all exceptions regardless of type, and then execute some generic additional logic?

Answer: To catch all exceptions, you could use the code in the following code example.

try

{

 

// Your logic.

}

catch

{

 

// Logic to execute in the event of an exception.

}

Using Exception Properties

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

Answer: The Message and Source properties.

Using a Finally Block

Question: Describe the differences between a catch block and a finally block.

Answer: A catch block contains code that executes only when a matching exception is thrown. A finally block contains code that always executes, regardless of whether an exception is thrown.

Using the Checked and Unchecked Keywords

Question: In what scenario would you want to use the checked keyword?

Answer: By default, overflow checking is enabled. You may want to use the checked keyword if overflow checking has been disabled during compilation or in the runtime.

4-4

Programming in C# with Microsoft© Visual Studio© 2010

Demonstration: Raising Exceptions in Visual Studio

Question: How can you guarantee that Visual Studio will always notify you if an exception occurs instead of automatically propagating the exception to a catch block?

Answer: You can use the Exceptions dialog box to configure the exception as Thrown instead of User-Handled.

Handling Exceptions

4-5

Detailed Demo Steps

Demonstration: Raising Exceptions in Visual Studio Demonstration Steps

Task 1: Open the existing application and view the existing code

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

2. In Visual Studio 2010, on the File menu, click Open, and then click Project/Solution.

3. In the Open Project dialog box, move to the E:\Demofiles\Mod4\Demo1\Starter\FabrikamUserManagement folder, and then double- click FabrikamUserManagement.sln.

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

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

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

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

d. The method call is in a try/catch block.

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

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

1. On the Debug menu, click Start Debugging.

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

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

4. Explain that, because the code is enclosed in a try/catch block, the exception was caught and error logic was executed.

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

6. On the Debug menu, click Stop Debugging.

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

1. On the Debug menu, click Exception.

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

4-6

Programming in C# with Microsoft© Visual Studio© 2010

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

5. In the Break when an exception is list, under System, locate the System.NullReferenceException row.

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

7. In the Exceptions dialog box, click OK.

Task 4: Rerun the application and examine the different behavior

1. On the Debug menu, click Start Debugging.

2. Explain that this time, when the application tries to use the user object and generates a null reference exception, Visual Studio stops the application and notifies you.

3. Explain that you can then use the debug Step Over function to walk through the logic in the catch block.

Handling Exceptions

4-7

Additional Reading

Using a Try/Catch Block

For more information about try/catch blocks, see the try-catch (C# Reference) page at

Using Exception Properties

For more information about the members in the System.Exception class, see the Exception Members page at http://go.microsoft.com/fwlink/?LinkId=192912.

Using a Finally Block

For more information about finally block, see the try-finally (C# Reference) page at

Using the Checked and Unchecked Keywords

For more information about using the checked and unchecked keywords, see the Checked and Unchecked (C# Reference) page at http://go.microsoft.com/fwlink/?LinkId=192914.

4-8

Programming in C# with Microsoft© Visual Studio© 2010

Lesson 2

Raising Exceptions

Contents:

Question and Answers

9

Handling Exceptions

4-9

Question and Answers

Creating an Exception Object

Question: You are in the process of adding several new methods to your application. So far you have added the method signatures. What else should you do to indicate that the method is not complete and functional?

Answer: You should throw a NotImplementedException exception. Syntax for throwing an exception is covered in the next topic.

Throwing an Exception

Question: Where does execution continue after you perform a throw statement?

Answer: The next catch block in the call stack.

Best Practices for Handling and Raising Exceptions

Question: In your application, you have a method that returns a user object. When you have the user object, you are going to use it as a parameter in another method call. There is a possibility that some of the data in the user object is incorrectly formatted and that, if you try to use this data, it would cause an exception. What would you do in this situation?

Answer: The point here is that you shouldn’t rely on exception handling for normal processing. In this example, it would be best to test whether the data is in the correct format before processing, rather than just hoping it works and doesn’t throw an exception. Explain that, in some scenarios, this can be a tough decision.

4-10

Programming in C# with Microsoft© Visual Studio© 2010

Module Review and Takeaways

Review Questions

1. In your application, you have a method call that depends on many variables that are out of the control of your application. It is very likely that this method call will throw an exception. You have implemented a centralized exception-handling system so that all exceptions are caught and handled in a single place. When you make the method call, if an exception is thrown, you just want to ensure that you manage and close any resources. Which construct would you use?

Answer: The try/finally construct.

2. In your application, you have defined several custom exception classes. You have several catch blocks that catch this type of exception. In your catch blocks, you want to wrap this type of exception in a more generic exception type. What constructor parameter can you set to ensure that the more specific exception is included in the chain?

Answer: The InnerException parameter.

3. What should you do with detailed exception messages?

Answer: Log them because they will help you diagnose problems in your application. Do not display them to the user.

Best Practices Related to Implementing Exception Handling

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

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

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

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

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

Handling Exceptions

4-11

Lab Review Questions and Answers

1. What construct did you use to make the method calls fail-safe?

Answer: The try/catch block.

2. What attribute did you need to decorate the test method with so that it expected an exception?

Answer: The ExpectedException attribute, specifying the type of exception expected.

3. What keyword can you use to explicitly instruct the compiler or runtime to check for overflow exceptions?

Answer: The checked keyword.

Reading and Writing Files

5-1

Module 5

Reading and Writing Files

Contents:

Lesson 1: Accessing the File System

2

Lesson 2: Reading and Writing Files by Using Streams

5

Module Review and Takeaways

8

Lab Review Questions and Answers

9

5-2

Programming in C# with Microsoft© Visual Studio© 2010

Lesson 1

Accessing the File System

Contents:

Question and Answers

3

Additional Reading

4

Reading and Writing Files

5-3

Question and Answers

Manipulating Files

Question: In your application, you use files as a temporary storage mechanism while the application is running. When the application stops running, you want to make sure that the file exists, and then delete the file. What is the easiest way to achieve this?

Answer: The easiest approach would be to use the static Exists and Delete methods of the File class.

Reading from and Writing to Files

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

Answer: The AppendAllText method.

Manipulating Directories

Question: What class would you use to retrieve an instance of a directory in the file system, which you can then interact with?

Answer: You would create an instance of the DirectoryInfo class by using the default constructor passing in the path to the directory.

Manipulating Paths

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

Answer: The GetExtension and GetFileName methods.

Using the Common File System Dialog Boxes

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

Answer: You would use the SaveFileDialog class in the following way:

1. Create an instance of the SaveFileDialog class.

2. Set any properties to customize its behavior.

3. Call the ShowDialog method to show the dialog box.

4. Use the result returned in the FileName property.

5-4

Programming in C# with Microsoft© Visual Studio© 2010

Additional Reading

Manipulating Files

For more information about the File class, see the File Class page at

For more information about the FileInfo class, see the FileInfo Class page at

Manipulating Directories

For more information about the Directory class, see the Directory Class page at

For more information about the DirectoryInfo class, see the DirectoryInfo Class page at

Manipulating Paths

For more information about the Path class, see the Path Class page at

Reading and Writing Files

5-5

Lesson 2

Reading and Writing Files by Using Streams

Contents:

Question and Answers

6

Additional Reading

7

5-6

Programming in C# with Microsoft© Visual Studio© 2010

Question and Answers

What Are Streams?

Question: What do you think are the benefits of streaming data?

Answer: Answers should include:

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

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

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

Reading and Writing Binary Data

Question: Why is it important to close streams when you have finished using them?

Answer: To release any file handles, and flush data to the underlying streams.

Reading and Writing Text

Question: You want to write a series of strings to a text file, and add a line break after each string. What is the easiest way to achieve this?

Answer: Write the string by using the WriteLine method of the StreamWriter class.

Reading and Writing Primitive Data Types

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

Answer: The ReadInt64() method.

Reading and Writing Files

5-7

Additional Reading

What Are Streams?

For more information about the FileStream class, see the FileStream Class page at

Reading and Writing Text

For more information about the StreamWriter class, see the StreamWriter Class page at

For more information about the StreamReader class, see the StreamReader Class page at

Reading and Writing Primitive Data Types

For more information about the BinaryWriter class, see the BinaryWriter Class page at

For more information about the BinaryReader class, see the BinaryReader Class page at

5-8

Programming in C# with Microsoft© Visual Studio© 2010

Module Review and Takeaways

Review Questions

1. When you write data to a stream, name two methods that you could use to ensure that any buffered data is written to the underlying data source.

Answer: You could call the Flush or Close methods.

2. Which two classes does the .NET Framework provide that display a graphical control that enables you to capture a save file and open file path from a user?

Answer: The SaveFileDialog and OpenFileDialog classes.

3. Which stream class would you use to write textual data?

Answer: The StreamWriter class.

Best Practices Related to Reading and Writing Data on the File System

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

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

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

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

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

Reading and Writing Files

5-9

Lab Review Questions and Answers

1. Explain the purpose of the File.Load and File.Save static methods.

Answer:

You call the File.Load method passing the file path as the parameter. The method returns a string that contains the full contents of the file.

You call the File.Save method passing the file path and text content as parameters. The text content parameter is stored in a file at the file path on the hard disk.

2. You have a file that contains text. You want to read the file one character at a time. Which method of the StreamReader class would you use?

Answer: The Read method.

Creating New Types

6-1

Module 6

Creating New Types

Contents:

Lesson 1: Creating and Using Enumerations

2

Lesson 2: Creating and Using Classes

5

Lesson 3: Creating and Using Structures

9

Lesson 4: Comparing References to Values

11

Module Review and Takeaways

15

Lab Review Questions and Answers

16

6-2

Programming in C# with Microsoft© Visual Studio© 2010

Lesson 1

Creating and Using Enumerations

Contents:

Question and Answers

3

Additional Reading

4

Creating New Types

6-3

Question and Answers

What Are Enumerations?

Question: Discuss with other students and the instructor where and how you have used enumerations before.

Answer: This question is designed to stimulate discussion among the students, so there is no definitive answer.

Creating New Enum Types

Question: Does the following code example show a legal enumeration?

enum Season : sbyte {Spring = -3, Summer, Fall, Winter};

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

Initializing and Assigning Enum Variables

Question: Describe how to initialize an enumeration variable.

Answer: You should do the following:

Specify the type of enumeration.

Specify the name of the instance.

Assign a value by using the = operator.

6-4

Programming in C# with Microsoft© Visual Studio© 2010

Additional Reading

Creating New Enum Types

For more information about enumerations, see the Enumeration Types (C# Programming Guide) page at

Creating New Types

6-5

Lesson 2

Creating and Using Classes

Contents:

Question and Answers

6

Additional Reading

8

6-6

Programming in C# with Microsoft© Visual Studio© 2010

Question and Answers

What Is a Class?

Question: Explain the difference between a class and an object.

Answer: A class is a blueprint that defines the characteristics of an object, such as the data that the object can contain and the operations that the object can perform.

An object is an instance of a class. You can use a single class to create as many objects as your application requires.

Adding Members to Classes

Question: What is the difference between a field and a method?

Answer: Fields hold data whereas methods expose functionality.

Defining Constructors and Initializing an Object

Question: What happens if you do not define a default constructor for a class?

Answer: If you do not define any constructors, a default parameterless constructor will be provided. If you define one or more constructors, a default parameterless constructor will not be provided.

Creating Objects

Question: Which operator must you use when you initialize a class to create an instance of that class?

Answer: The new operator.

Accessing Class Members

Question: Highlight the syntax errors in the following code example.

Car myCar = new Car("Ford", "Black"); // Set a field to indicate the car's transmission. myCar,isManual() = true; // Call a method to calculate the car's value. double value = myCar,CalculateValue;

Answer: The following code example highlights the errors.

Car myCar = new Car("Ford", "Black"); // Set a field to indicate the car's transmission. myCar,isManual() = true; // Comma should be period, and no parentheses. // Call a method to calculate the car's value. double value = myCar,CalculateValue; // Comma should be period, and parentheses required.

Creating New Types

6-7

Using Partial Classes and Partial Methods

Question: What happens if you define a partial method, but do not provide an implementation of this method?

Answer: Your code will still compile and run, and you will be able to call the method. However, because the method contains no implementation, it will not do anything.

6-8

Programming in C# with Microsoft© Visual Studio© 2010

Additional Reading

Defining Constructors and Initializing an Object

For more information about constructors, see the Instance Constructors (C# Programming Guide) page at

Using Partial Classes and Partial Methods

For more information about partial classes and methods, see the Partial Classes and Methods (C# Programming Guide) page at http://go.microsoft.com/fwlink/?LinkId=192927.

Creating New Types

6-9

Lesson 3

Creating and Using Structures

Contents:

Question and Answers

10

6-10

Programming in C# with Microsoft© Visual Studio© 2010

Question and Answers

What Are Structures?

Question: Is the following code legal?

int x = 99; System.Int32 y = x + 1;

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

Defining and Using a Structure

Question: What keyword do you use to declare a structure?

Answer: The struct keyword.

Initializing a Structure

Question: You decide to add further constructors to the Currency type, and you attempt to factor out common initialization code into a method in the type, as shown in the following code example. Why does this approach not work?

struct Currency

{

public string currencyCode;

// The ISO 4217 currency code

public string currencySymbol; // The currency symbol ($,£,

)

public int fractionDigits;

// The number of decimal places

public Currency(string code)

{

this.initialize(); this.currencyCode = code;

}

public Currency(string code, string symbol)

 

{

this.initialize(); this.currencyCode = code; this.currencySymbol = symbol;

 

}

// Specify default values

// Constructors may override these values public void initialize()

 

{

this.currencyCode = "USD"; this.currencySymbol = "$"; this.fractionDigits = 2;

}

};

Answer: Before you can call any methods in a structure, you must ensure that all of the fields in the structure have been initialized. Consequently, you cannot call methods in a constructor to initialize fields in that structure, so this code will not compile. Note that this code would be legal if the Currency type was a class.

Creating New Types

6-11

Lesson 4

Comparing References to Values

Contents:

Question and Answers

12

Additional Reading

14

6-12

Programming in C# with Microsoft© Visual Studio© 2010

Question and Answers

Comparing Reference Types to Value Types

Question: If Residence is a class (a reference type), what message does the following code example display?

Residence myHouse = new Residence(ResidenceType.House, 2); Residence anotherHouse = new Residence(ResidenceType.House, 2); if (myHouse == anotherHouse)

{

 

Console.WriteLine("They are the same house");

}

else

{

 

Console.WriteLine("They are different houses");

}

Answer: The message “They are different houses” is displayed because they are different objects, although both are of type Residence. If the Residence type was a struct, the code would not compile unless the Residence definition included an implementation for the == operator.

Passing a Value Type by Reference into a Method

Question: In the following code example, what is the value of the myString variable after the ChangeInput method completes?

class Program

{

 

static void Main(string[] args)

{

string myString = "Original value"; ChangeInput(myString);

}

static void ChangeInput(string input)

{

input = "Changed value";

}

}

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

Boxing and Unboxing

Question: Is the following code an example of boxing or unboxing?

object amount = "1234"; int convertedAmount = (int)amount;

Answer: Unboxing.

Creating New Types

6-13

Nullable Types

Question: What is wrong with the following code?

int amount = null; if (amount != null)

{

}

Answer: The int variable amount has not been declared by using the nullable int type. The following code example illustrates this.

int? i = null;

6-14

Programming in C# with Microsoft© Visual Studio© 2010

Additional Reading

Passing a Value Type by Reference into a Method

For more information about using the ref keyword, see the ref (C# Reference) page at

Boxing and Unboxing

For more information about boxing and unboxing, see the Boxing and Unboxing (C# Programming Guide) page at http://go.microsoft.com/fwlink/?LinkId=192929.

Creating New Types

6-15

Module Review and Takeaways

Review Questions

1. When you define the first value in an enumeration, the value defaults to the index of zero. How can you change the default index?

Answer:

enum Days : int { Monday = 1, Tuesday = 2, Wednesday = 3 };

2. What is a class?

Answer: A class is a blueprint from which you can create objects. A class defines the characteristics of an object, such as the data that the object can contain and the operations that the object can perform.

3. What keyword can you use to split a class definition over multiple files?

Answer: The partial keyword.

4. Is a Boolean variable a value type or a reference type?

Answer: A value type.

5. How can you pass a value type by reference into a method?

Answer: By using the ref keyword.

6. What is the process called when you explicitly convert a value type to a reference type?

Answer: Boxing.

Best Practices Related to Creating and Using Types

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

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

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

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

6-16

Programming in C# with Microsoft© Visual Studio© 2010

Lab Review Questions and Answers

1. What type would you use to model a collection of constant values?

Answer: An enumeration type.

2. At what scope level would you define an enumeration type, if you wanted that type to be accessible to multiple classes?

Answer: At the namespace scope level.

3. What construct would you use to model a simple custom numeric type?

Answer: A struct type.

Encapsulating Data and Methods

7-1

Module 7

Encapsulating Data and Methods

Contents:

Lesson 1: Controlling Visibility of Type Members

2

Lesson 2: Sharing Methods and Data

5

Module Review and Takeaways

9

Lab Review Questions and Answers

10

7-2

Programming in C# with Microsoft© Visual Studio© 2010

Lesson 1

Controlling Visibility of Type Members

Contents:

Question and Answers

3

Additional Reading

4

Encapsulating Data and Methods

7-3

Question and Answers

What Is Encapsulation?

Question: Discuss your experiences of encapsulation with other students.

Answer: This question is designed to stimulate discussion among the students, so there is no definitive answer.

Comparing Private and Public Members

Question: You have created a class called Product to encapsulate information about the products that your organization sells. The following code example shows the definition of this class. You want to use this class in an application that creates Product objects and displays their details. What is the main problem with the Product class that may mean that a client application cannot use the Product type in this way?

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

public class Product

{

 

// Make these fields private so that an application cannot change // them after the Product object has been created. private int productID; private string productName; // Public methods that a client application can use to // get the product ID and name. public int GetProductID()

{

return this.productID;

}

public string GetProductName()

{

return this.productName;

}

// Provide a constructor to enable a client application // to create a Product object. Product(int ID, string name)

{

this.productID = ID; this.productName = name;

}

}

Comparing Internal and Public Types

Question: In the Revenue structure that is shown in the preceding code example, the constructor is defined as public although the type is defined as private. Does this mean that a type other than the Sales type can invoke this constructor?

Answer: The Revenue struct is only accessible to the Sales type.

7-4

Programming in C# with Microsoft© Visual Studio© 2010

Additional Reading

What Is Encapsulation?

For more information about encapsulation, see the Classes and Structs (C# Programming Guide) page at

Comparing Private and Public Members

For more information about the private access modifier, see the private (C# Reference) page at

For more information about the public access modifier, see the public (C# Reference) page at

Comparing Internal and Public Types

For more information about the internal access modifier, see the internal (C# Reference) page at

Encapsulating Data and Methods

7-5

Lesson 2

Sharing Methods and Data

Contents:

Question and Answers

6

Additional Reading

8

7-6

Programming in C# with Microsoft© Visual Studio© 2010

Question and Answers

Creating and Using Static Fields

Question: What happens if you try to access a public static field through an instance of the type?

Answer: You get a compile error that explains that the member cannot be accessed with an instance reference.

Creating and Using Static Methods

Question: The Person class definition in the following code example contains functionality to calculate the number of years that a person must work before he or she reaches a set retirement age. The class does not compile; can you identify the problem?

class Person