M I CRO S O F T
L EA RN I N G
PRO DU C T
10266A
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.
1-1
Module 1
Introducing C# and the .NET Framework
Contents:
Lesson 1: Introduction to the .NET Framework 4 Lesson 2: Creating Projects Within Visual Studio 2010 Lesson 3: Writing a C# Application Lesson 4: Building a Graphical Application Lesson 5: Documenting an Application Lesson 6: Debugging Applications by Using Visual Studio 2010 Module Review and Takeaways Lab Review Questions and Answers 2 5 9 12 17 20 22 24
1-2
Lesson 1
1-3
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. 2. 3. The Class Loader locates and loads all assemblies that the application requires. The assemblies will already be compiled into MSIL. The MSIL-to-native compiler verifies the MSIL code and then compiles all assemblies into machine code ready for execution. The Code Manager loads the executable assembly and runs the Main method.
1-4
Additional Reading
What Is the .NET Framework 4?
For more information about the .NET Framework, see the Microsoft .NET page at http://go.microsoft.com/fwlink/?LinkId=192876.
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 http://go.microsoft.com/fwlink/?LinkId=192880. For more information about assembly signing, see the SignTool.exe (Sign Tool) page at http://go.microsoft.com/fwlink/?LinkId=192881.
1-5
Lesson 2
1-6
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.
1-7
Answer: You can build a .NET application by using Visual Studio or csc.exe on the command line.
1-8
1-9
Lesson 3
Writing a C# Application
Contents:
Question and Answers Additional Reading 10 11
1-10
Answer: The correct answer is: Console.WriteLine("Please press any key); ConsoleKeyInfo keyPressed = Console.ReadKey();
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.
1-12
Lesson 4
1-13
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.
1-14
1-15
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
Additional Reading
What Is WPF?
For more information about what WPF is, see the Introduction to WPF page at http://go.microsoft.com/fwlink/?LinkId=192884.
WPF Events
For more information about how WPF handles events, see the Events (WPF) page at http://msdn.microsoft.com/en-us/library/ms753115(VS.100).aspx.
1-17
Lesson 5
Documenting an Application
Contents:
Question and Answers Additional Reading 18 19
1-18
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.
1-20
Lesson 6
1-21
Using Breakpoints
Question: How would you use the debug functions in Visual Studio 2010 to debug your application and pause on a specific line of code? Answer: Answers should include: 1. 2. Locate the line of interest and set a breakpoint. Start the application with debugging.
1-22
1-23
Tools
Tool Caspol.exe Use for Where to find it Enables users to modify the machine, user, and enterprise C:\Windows\Microsoft.NET\Frame security policy. This can include defining a custom work\v4.0.30319 permission set and adding assemblies to the full trust list. 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. Enables users to manipulate assemblies, such as determining whether an assembly is managed, or disassembling an assembly to view the compiled MSIL code. 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 C:\Program Files\Microsoft SDKs\Windows\v7.0A\bin
Gacutil.exe
Ildasm.exe
Makecert.exe
Ngen.exe
Enables users to improve the performance of .NET C:\Windows\Microsoft.NET\Frame applications. The Native Image Generator improves work\v4.0.30319 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. 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
Sn.exe
1-24
2-1
Module 2
Using C# Programming Constructs
Contents:
Lesson 1: Declaring Variables and Assigning Values Lesson 2: Using Expressions and Operators Lesson 3: Creating and Using Arrays Lesson 4: Using Decision Statements Lesson 5: Using Iteration Statements Module Review and Takeaways Lab Review Questions and Answers 2 5 8 11 14 16 17
2-2
Lesson 1
2-3
2-4
Additional Reading
Declaring and Assigning Variables
For more information about the keyword in C#, see the C# Keywords page at http://go.microsoft.com/fwlink/?LinkId=192890. For more information about naming conventions, see the General Naming Conventions page at http://go.microsoft.com/fwlink/?LinkId=192891. For more information about capitalization conventions, see the Capitalization Conventions page at http://go.microsoft.com/fwlink/?LinkId=192892.
2-5
Lesson 2
2-6
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 http://go.microsoft.com/fwlink/?LinkId=192897
2-8
Lesson 3
2-9
2-10
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 http://go.microsoft.com/fwlink/?LinkId=192899. 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 http://go.microsoft.com/fwlink/?LinkId=192902.
2-11
Lesson 4
2-12
2-13
Additional Reading
Using Either-Or If Statements
For more information about the ?: operator, see the ?: Operator (C# Reference) page at http://go.microsoft.com/fwlink/?LinkId=192904.
2-14
Lesson 5
2-15
2-16
2-17
3-1
Module 3
Declaring and Calling Methods
Contents:
Lesson 1: Defining and Invoking Methods Lesson 2: Specifying Optional Parameters and Output Parameters Module Review and Takeaways Lab Review Questions and Answers 2 9 12 13
3-2
Lesson 1
3-3
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");
3-4
Testing a Method
Question: Why would you want to use unit tests when developing your .NET Framework applications? Answer: Unit tests provide an excellent way to help simplify the testing process and ensure that your tests are reliable and easily repeatable.
3-5
4. 5.
2. 3.
Right-click the selected code block, point to Refactor, and then click Extract Method. In the Extract Method dialog box, perform the following, and then click OK: a. b. In the New method name box, type GenerateRandomNumbers 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.
3-6
a. b. 3. 4.
In the Current selection list, show students the available components in the project. In the Output project list, explain that if the solution already contained a test project, you could select it here.
In the New Test Project dialog box, click Create. In the Add InternalsVisibleTo Attribute dialog box, click Yes.
2.
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. 5. 6.
In the Code Editor window, navigate to the GenerateRandomNumbersTest method, and then set the numberOfRequirednumbers variable to 1000. In the Test View window, right-click the GenerateRandomNumbersTest row, and then click Run Selection. Show students the Test Results window, and that the unit test succeeded.
3-8
Additional Reading
Creating a Method
For more information about methods, see the Methods (C# Programming Guide) page at http://go.microsoft.com/fwlink/?LinkId=192905.
3-9
Lesson 2
3-10
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.
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.
3-12
3-13
Handling Exceptions
4-1
Module 4
Handling Exceptions
Contents:
Lesson 1: Handling Exceptions Lesson 2: Raising Exceptions Module Review and Takeaways Lab Review Questions and Answers 2 8 10 11
4-2
Lesson 1
Handling Exceptions
Contents:
Question and Answers Detailed Demo Steps Additional Reading 3 5 7
Handling Exceptions
4-3
4-4
Handling Exceptions
4-5
4.
Task 2: Run the application and examine how it currently handles exceptions
1. 2. 3. On the Debug menu, click Start Debugging. Switch to the Command Prompt window, and show students the Object reference not set to an instance of an object message. 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. Explain that, because the code is enclosed in a try/catch block, the exception was caught and error logic was executed. 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. On the Debug menu, click Stop Debugging.
4. 5.
6.
Task 3: Modify the exception configuration in Visual Studio to always throw exceptions
1. 2. 3. On the Debug menu, click Exception. In the Exceptions dialog box, in the Break when an exception is list, expand Common Language Runtime Exceptions, and then expand System. Explain that, by using this list and the associated Thrown and User-unhandled check boxes, you can control how Visual Studio notifies you when an exception is generated.
4-6
4. 5. 6. 7.
Explain that the code in our application generated a null reference exception, so that is the type of exception that we will modify. In the Break when an exception is list, under System, locate the System.NullReferenceException row. For the System.NullReferenceException row, clear the User-unhandled check box, and then select the Thrown check box. In the Exceptions dialog box, click OK.
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 http://go.microsoft.com/fwlink/?LinkId=192911.
4-8
Lesson 2
Raising Exceptions
Contents:
Question and Answers 9
Handling Exceptions
4-9
Throwing an Exception
Question: Where does execution continue after you perform a throw statement? Answer: The next catch block in the call stack.
4-10
Handling Exceptions
4-11
5-1
Module 5
Reading and Writing Files
Contents:
Lesson 1: Accessing the File System Lesson 2: Reading and Writing Files by Using Streams Module Review and Takeaways Lab Review Questions and Answers 2 5 8 9
5-2
Lesson 1
5-3
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.
5-4
Additional Reading
Manipulating Files
For more information about the File class, see the File Class page at http://go.microsoft.com/fwlink/?LinkId=192915. For more information about the FileInfo class, see the FileInfo Class page at http://go.microsoft.com/fwlink/?LinkId=192916.
Manipulating Directories
For more information about the Directory class, see the Directory Class page at http://go.microsoft.com/fwlink/?LinkId=192917. For more information about the DirectoryInfo class, see the DirectoryInfo Class page at http://go.microsoft.com/fwlink/?LinkId=192918.
Manipulating Paths
For more information about the Path class, see the Path Class page at http://go.microsoft.com/fwlink/?LinkId=192919.
5-5
Lesson 2
5-6
5-7
Additional Reading
What Are Streams?
For more information about the FileStream class, see the FileStream Class page at http://go.microsoft.com/fwlink/?LinkId=192920.
5-8
Best Practices Related to Reading and Writing Data on the File System
Supplement or modify the following best practices for your own work situations: Always check to make sure that the file exists before you try to read from it or write to it. Do not assume that the contents in the file are going to be correct. Remember that files are stored on the file system, which users have access to. Users are more than capable of editing a file that they should not edit. Always parse a file to ensure that it is valid, or be prepared to catch and handle an appropriate exception. When you use streams, always ensure that you close the stream after use to ensure that you release any handles on the underlying data source. It is easy to assume that you will have permissions to write and read files anywhere in the live environment. Typically, this is not the case. Make sure that your development environment mirrors the live environment.
5-9
6-1
Module 6
Creating New Types
Contents:
Lesson 1: Creating and Using Enumerations Lesson 2: Creating and Using Classes Lesson 3: Creating and Using Structures Lesson 4: Comparing References to Values Module Review and Takeaways Lab Review Questions and Answers 2 5 9 11 15 16
6-2
Lesson 1
6-3
Answer: Yes. The signed byte type allows negative numbers. The value assigned to Spring is 3, Summer has the value 2, Fall has the value 1, and Winter has the value 0.
6-4
Additional Reading
Creating New Enum Types
For more information about enumerations, see the Enumeration Types (C# Programming Guide) page at http://go.microsoft.com/fwlink/?LinkId=192925.
6-5
Lesson 2
6-6
Creating Objects
Question: Which operator must you use when you initialize a class to create an instance of that class? Answer: The new operator.
6-7
6-8
Additional Reading
Defining Constructors and Initializing an Object
For more information about constructors, see the Instance Constructors (C# Programming Guide) page at http://go.microsoft.com/fwlink/?LinkId=192926.
6-9
Lesson 3
6-10
Answer: Yes. It is legal because the int type is an alias for the System.Int32 type.
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.
6-11
Lesson 4
6-12
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.
Answer: The value of the myString variable is Original Value. The issue is that the reference is passed as the parameter. You can change data through the reference, but if you make the reference refer somewhere else, it is lost when the method completes, and the original data is left intact.
Answer: Unboxing.
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
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 http://go.microsoft.com/fwlink/?LinkId=192928.
6-15
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.
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.
6-16
7-1
Module 7
Encapsulating Data and Methods
Contents:
Lesson 1: Controlling Visibility of Type Members Lesson 2: Sharing Methods and Data Module Review and Takeaways Lab Review Questions and Answers 2 5 9 10
7-2
Lesson 1
7-3
7-4
Additional Reading
What Is Encapsulation?
For more information about encapsulation, see the Classes and Structs (C# Programming Guide) page at http://go.microsoft.com/fwlink/?LinkId=192935.
7-5
Lesson 2
7-6
Answer: The CalculateRemainingWorkYears method is static, but the retirementAge field is an instance.
Answer: The class has the following errors: You cannot explicitly set an access modifier on a static constructor. The constructor must be parameterless. A static constructor cannot access an instance field.
7-7
7-8
Additional Reading
Creating and Using Static Methods
For more information about the static modifier, see the static (C# Reference) page at http://go.microsoft.com/fwlink/?LinkId=192933.
7-9
7-10
8-1
Module 8
Inheriting from Classes and Implementing Interfaces
Contents:
Lesson 1: Using Inheritance to Define New Reference Types Lesson 2: Defining and Implementing Interfaces Lesson 3: Defining Abstract Classes Module Review and Takeaways Lab Review Questions and Answers 2 8 13 19 20
8-2
Lesson 1
8-3
Understanding Polymorphism
Question: When you reference an object by its parent class, which version of a method is called: the version from the base class, or the overridden version in the child class? Answer: When a method is overridden in the child class, the version in the child class will always be used. Referencing an object by using the parent class will not change this behavior.
8-4
8-5
Add a Television class to the Program.cs file: a. b. In Solution Explorer, double-click Program.cs. Add the following code to the file.
class Television { }
5.
Add a protected virtual method named SetCurrentChannel to the Television class. The method should write a message to the console indicating that the channel has been set. Your code should resemble the following code example.
class Television { protected virtual void SetCurrentChannel() { Console.WriteLine(Channel set.); } }
6.
Add a protected method named TurnOn to the Television class. The method should write a message to the console indicating that the television is on. Your code should resemble the following code example.
class Television { protected virtual void SetCurrentChannel() { Console.WriteLine(Channel set.). } protected void TurnOn() { Console.WriteLine(Television on.); }
8-6
7.
Add to the Program.cs file a WidescreenTV class that inherits from the Television class: Add the code in the following code example to the file.
class WidescreenTV : Television { }
8.
Override the SetCurrentChannel method. The method should write a message to the screen indicating that the channel has been set on the widescreen television. Your code should resemble the following code example.
class WidescreenTV : Television { protected override void SetCurrentChannel() { Console.WriteLine(Widescreen channel set.); } }
9.
Add a constructor to the WidescreenTV class. The constructor should call the constructor of the base class, call the TurnOn method, call the SetCurrentChannel method, and then call the SetCurrentChannel method of the base class. Your code should resemble the following code example.
class WidescreenTV : Television { protected override void SetCurrentChannel() { Console.WriteLine(Widescreen channel set.); } public WidescreenTV() : base() { TurnOn(); SetCurrentChannel(); base.SetCurrentChannel(); } }
10. Uncomment the code in the Program class that creates an instance of the WidescreenTV class. 11. Run the application with debugging and verify that the following messages appear: Television on. Widescreen channel set. Channel set.
8-7
Additional Reading
The .NET Framework Inheritance Hierarchy
For more information about the Object class, see the Object Class page at http://go.microsoft.com/fwlink/?LinkId=192936.
Understanding Polymorphism
For more information about polymorphism, see the Polymorphism (C# Programming Guide) page at http://go.microsoft.com/fwlink/?LinkId=192937.
8-8
Lesson 2
8-9
8-10
Add an ITelevision interface to the Program.cs file: a. b. In Solution Explorer, double-click Program.cs. Add the code in the following code example to the file.
interface ITelevision { }
4.
Add a TurnOn method to the interface. Your code should resemble the following code example.
interface ITelevision { void TurnOn(); }
5.
Add a TurnOff method to the interface. Your code should resemble the following code example.
interface ITelevision { void TurnOn(); void TurnOff(); }
6.
Add an IncreaseVolume method to the interface. Your code should resemble the following code example.
interface ITelevision { void TurnOn(); void TurnOff(); void IncreaseVolume(); }
7.
Add a DecreaseVolume method to the interface. Your code should resemble the following code example.
8-11
interface ITelevision { void TurnOn(); void TurnOff(); void IncreaseVolume(); void DecreaseVolume(); }
8.
Add to the Program.cs file a Television class that implements the ITelevision interface: Add the code in the following code example to the file.
class Television : ITelevision { }
9.
In the definition of the Television class, implement the ITelevision interface by using the tools in Visual Studio: Right-click ITelevision, point to Implement Interface, and then click Implement Interface.
8-12
Additional Reading
Explicitly and Implicitly Implementing an Interface
For more information about how to explicitly implement interface members, see the Explicit Interface Implementation (C# Programming Guide) page at http://go.microsoft.com/fwlink/?LinkId=192938.
8-13
Lesson 3
8-14
8-15
Add a Television abstract class to the Program.cs file: a. b. In Solution Explorer, double-click Program.cs. Add the code in the following code example to the file.
abstract class Television { }
4.
Add a public TurnOn method to the class. The method should write a message to the console indicating that the television is on. Your code should resemble the following code example.
abstract class Television { public void TurnOn() { Console.WriteLine(Television on.); } }
5.
Add a public TurnOff method to the class. The method should write a message to the console indicating that the television is off. Your code should resemble the following code example.
abstract class Television { public void TurnOn() { Console.WriteLine(Television on.); } public void TurnOff() { Console.WriteLine(Television off.); } }
6.
Add a public abstract IncreaseVolume method to the class. Your code should resemble the following code example.
8-16
abstract class Television { public void TurnOn() { Console.WriteLine(Television on.); } public void TurnOff() { Console.WriteLine(Television off.); } public abstract void IncreaseVolume(); }
7.
Add a public abstract DecreaseVolume method to the class. Your code should resemble the following code example.
abstract class Television { public void TurnOn() { Console.WriteLine(Television on.); } public void TurnOff() { Console.WriteLine(Television off.); } public abstract void IncreaseVolume(); public abstract void DecreaseVolume(); }
8.
Add to the Program.cs file a WidescreenTV class that inherits from the abstract Television class: Add the code in the following code example to the file.
class WidescreenTV : Television { }
9.
Override the IncreaseVolume method. The method should write a message to the screen indicating that the volume has increased on the widescreen television. Your code should resemble the following code example.
class WidescreenTV : Television { public override void IncreaseVolume() { Console.WriteLine(Volume increased (WidescreenTV).); } }
10. Override the DecreaseVolume method. The method should write a message to the screen indicating that the volume has decreased on the widescreen television. Your code should resemble the following code example.
class WidescreenTV : Television { public override void IncreaseVolume() {
8-17
Console.WriteLine(Volume increased (WidescreenTV).); } public override void DecreaseVolume() { Console.WriteLine(Volume decreased (WidescreenTV).); } }
11. Add to the Program.cs file a TV class that inherits from the abstract Television class: Add the code in the following code example to the file:
class TV : Television { }
12. Override the IncreaseVolume method. The method should write a message to the screen indicating that the volume has increased on the television. Your code should resemble the following code example.
class TV : Television { public override void IncreaseVolume() { Console.WriteLine(Volume increased (TV).); } }
13. Override the DecreaseVolume method. The method should write a message to the screen indicating that the volume has increased on the television. Your code should resemble the following code example.
class TV : Television { public override void IncreaseVolume() { Console.WriteLine(Volume increased (TV).); } public override void DecreaseVolume() { Console.WriteLine(Volume decreased (TV).); } }
14. Uncomment the code in the Program class. 15. Run the application: On the Debug menu, click Start Without Debugging.
8-18
Additional Reading
What Is an Abstract Class?
For more information about the abstract modifier, see the abstract (C# Reference) page at http://go.microsoft.com/fwlink/?LinkId=192940.
8-19
8-20
9-1
Module 9
Managing the Lifetime of Objects and Controlling Resources
Contents:
Lesson 1: Introduction to Garbage Collection Lesson 2: Managing Resources Module Review and Takeaways Lab Review Questions and Answers 2 7 12 13
9-2
Lesson 1
9-3
Defining a Destructor
Question: Can you add a destructor to a struct? Answer: No. You can only add a destructor to a class.
The GC Class
Question: How can you inform the runtime that you need to allocate a large block of unmanaged memory? Answer: You can use the AddMemoryPressure method of the GC class.
9-4
In the Employee.cs file, add a destructor to the Employee class. The destructor should write the current salary to the SalaryDetails.txt file: a. b. In Solution Explorer, double-click Employee.cs. the code in the following code example to the file.
~Employee() { File.WriteAllText(SalaryDetails.txt, salary.ToString()); Console.WriteLine(Employee finalized: {0}, name); }
4. 5.
Walk the students through the other code in the Employee class. Highlight the code that reads the current salary from a text file. Show the students the code in the Program.cs file. Highlight that each employee is given a pay rise and then the object reference is removed. Explain that this will make the object available for garbage collection and that the destructor will write the updated salary back to the file. Run the application: On the Debug menu, click Start Without Debugging.
6.
7.
Point out that all of the employees are paid the same amount; the pay rises do not reflect the update made to the text file by the destructor. Remind students that the garbage collector only runs when it needs to, and this program does not create enough objects or use enough memory to cause a collection. In the Program.cs file, uncomment the call to the AddMemoryPressure method. Explain that this makes the garbage collector free as much memory as possible ready for a large allocation of unmanaged memory. Run the application: On the Debug menu, click Start Without Debugging.
8.
9.
9-5
10. Explain that the results have not changedalthough the application now requires more memory, the application runs faster than the garbage collector finalizes the objects. 11. In the Program.cs file, uncomment the call to the WaitForPendingFinalizers method. 12. Run the application: On the Debug menu, click Start Without Debugging.
13. Highlight that the application now works as expected, because the application halts to wait for the finalizer to update the text file before continuing.
9-6
Additional Reading
Managed Resources in the .NET Framework
For more information about automatic memory management, see the 3.9 Automatic memory management page at http://go.microsoft.com/fwlink/?LinkId=192943.
Defining a Destructor
For more information about destructors, see the Destructors (C# Programming Guide) page at http://go.microsoft.com/fwlink/?LinkId=192944.
The GC Class
For more information about the GC class, see the GC Members page at http://go.microsoft.com/fwlink/?LinkId=192945.
9-7
Lesson 2
Managing Resources
Contents:
Question and Answers Detailed Demo Steps Additional Reading 8 9 11
9-8
9-9
Open the Module 9, Demo1 starter solution: a. b. On the File menu, point to Open, and then click Project/Solution. Move to the E:\Demofiles\Mod9\Demo2\Starter\Dispose Demo folder, and then double-click Dispose Demo.sln.
3.
Modify the Employee class to implement the IDisposable interface. The code should follow best practices. Explain to students that although the call to GC.SuppressFinalize in the Dispose method is unnecessary at present, it is still worth including it in case a finalizer is added to the Employee class later. Your completed code should resemble the following code example.
class Employee : IDisposable { bool isDisposed = false; string name; public Employee(string Name) { name = Name; } public void PaySalary() { if (!isDisposed) { Console.WriteLine("Employee {0} paid.", name); } else { throw new ObjectDisposedException("Employee already disposed."); } } public void Dispose() { Dispose(true); } protected virtual void Dispose(bool IsDisposing) { if (IsDisposing) { isDisposed = true; Console.WriteLine("Employee object disposed."); } GC.SuppressFinalize(this); }
9-10
4. 5.
Walk students through the Program class. Show them the using construct and the inline code. Explain that the using statement is exception safe and the inline code is not exception safe. Run the application: On the Debug menu, click Start Without Debugging.
6. 7.
When the application pauses, press ENTER. Point out the unhandled exception. Explain that the using statement prevented these exceptions.
9-11
Additional Reading
What Is the Dispose Pattern?
For more information about the Dispose method, see the Implementing a Dispose Method page at http://go.microsoft.com/fwlink/?LinkId=192946.
9-12
9-13
10-1
Module 10
Encapsulating Data and Defining Overloaded Operators
Contents:
Lesson 1: Creating and Using Properties Lesson 2: Creating and Using Indexers Lesson 3: Overloading Operators Module Review and Takeaways Lab Review Questions and Answers 2 8 12 16 17
10-2
Lesson 1
10-3
Defining a Property
Question: How can you enable write access to a property to other types in the same assembly, but read access to a property from a class in any assembly? Answer: Declare a public property, but mark the set accessor internal.
Automatic Properties
Question: What is the benefit of using an automatic property compared to exposing a public field? Answer: An automatic property is simply another property to consuming applications. If you must change your type in the future, and you must change a field to a property, any consuming application must be recompiled; however, if you simply change from an automatic property to a manually implemented property, the change is invisible to the consuming application.
10-4
Answer: If you are writing code for a secure environment where you must log access to the data.
10-5
Open the Employee.cs file, and then review the Employee class. Highlight the publicly exposed fields. Also highlight the constructor that sets the Name field based on the parameter and the Salary and Department fields to default values: In Solution Explorer, double-click Employee.cs, and then explain the contents of the class.
4.
Convert the Name field to a property by using automatic properties: Modify the following line of code.
public string Name;
5.
Convert the Department field to a property by using automatic properties: Modify the following line of code.
public string Department;
6.
Convert the public Salary field to a private field and rename it salary: Modify the following line of code.
public int Salary;
7. 8.
Uncomment the commented Salary property, and then explain how it ensures that an employee can never have a negative salary. Open the Program.cs file, and then review the Employee object.
10-6
In Solution Explorer, double-click Program.cs, and then explain the contents of the object. 9. Uncomment all of the code up to and including the first occurrence of the following code.
Console.ReadLine();
10. Describe the code that you have just uncommented: a. b. Explain how the julie object is created by using the constructor, and explain that the properties are subsequently set by using the dot notation. Explain how the james object is created by using named properties. Emphasize that these named properties are set after the constructor is run, so they take precedence over the default values set by the constructor.
11. Uncomment the remaining code in the file. 12. Describe the code that you have just uncommented: Explain that the code attempts to set James salary to a negative value. Remind students that the property prevented negative values. 13. Run the application: On the Debug menu, click Start Without Debugging. 14. When the application pauses, highlight that the application has worked as expected, and the two employees details are displayed correctly, and then press ENTER. 15. When the application pauses, highlight that the application has worked as expected, and James salary has been set to 0 instead of a negative value, and then press ENTER. 16. Close Visual Studio: In Visual Studio, on the File menu, click Exit.
10-7
Additional Reading
What Is a Property?
For more information about properties, see the Properties (C# Programming Guide) page at http://go.microsoft.com/fwlink/?LinkId=192948.
Defining a Property
For more information about using properties, see the Using Properties (C# Programming Guide) page at http://go.microsoft.com/fwlink/?LinkId=192949.
10-8
Lesson 2
10-9
Creating an Indexer
Question: What information should you use as parameters for an indexer? Answer: You should only use parameters that are necessary to locate an individual data member in the dataset. You should not use parameters to manipulate data.
10-10
3.
Open the EmployeeDatabase.cs file, and then review the EmployeeDatabase class: a. b. c. In Solution Explorer, double-click EmployeeDatabase.cs, and then describe the class. Highlight that the class stores an array of Employee objects. Highlight the AddToDatabase method, and then explain how it adds Employee objects to the array and increments a pointer to the top of the array.
4.
Uncomment the indexer that returns an Employee object. Explain how the indexer takes a string parameter called Name and iterates through each employee in the array until it finds one with a matching Name property. It then returns that value. If it does not find a match after iterating over the entire array, it returns null. Open the Program.cs file, and then describe the class: In the Program.cs file, uncomment the commented code, and then explain how this code uses the indexer to retrieve Employee instances by specifying the employee name. Remind students that this would not be possible with an array because you can only access an array by index. In Solution Explorer, double-click Program.cs, and then explain how the class creates an instance of the EmployeeDatabase class and then adds several Employee objects to the class.
5. 6.
7.
Run the application: On the Debug menu, click Start Without Debugging.
8. 9.
Highlight that the application runs as expected, and the details of the two employees retrieved from the database are displayed correctly, and then press ENTER. Close Visual Studio: In Visual Studio, on the File menu, click Exit.
10-11
Additional Reading
What Is an Indexer?
For more information about the comparison between properties and indexers, see the Comparison Between Properties and Indexers (C# Programming Guide) page at http://go.microsoft.com/fwlink/?LinkId=192952.
Creating an Indexer
For more information about using indexers, see the Using Indexers (C# Programming Guide) page at http://go.microsoft.com/fwlink/?LinkId=192953.
10-12
Lesson 3
Overloading Operators
Contents:
Question and Answers Detailed Demo Steps Additional Reading 13 14 15
10-13
Overloading an Operator
Question: Does the first operand of an overloaded operator have to be the containing type? Answer: No. At least one of the operands has to be the containing type, but there is no requirement for it to be the first operand.
10-14
Open the EmployeeDatabase.cs file, and then review the EmployeeDatabase class: a. b. In Solution Explorer, double-click EmployeeDatabase.cs, and then describe the class. Highlight that the class stores an array of Employee objects and is the same as in the previous demonstration.
4.
Uncomment the + operator that returns an EmployeeDatabase object. Explain how the + operator takes an EmployeeDatabase object and an Employee object as parameters, adds the Employee object to the database, and then returns a reference to the database. Open the Program.cs file, and then describe the class: In the Program.cs file, uncomment the commented code, and then explain how this code adds several Employee objects to the database by using both the + syntax and the += syntax. In Solution Explorer, double-click Program.cs, and then explain how the class creates an instance of the EmployeeDatabase class and then adds several Employee objects to the class.
5. 6.
7.
Run the application: On the Debug menu, click Start Without Debugging.
8. 9.
Highlight that the application runs as expected, and the details of the two employees retrieved from the database are displayed correctly, and then press ENTER. Close Visual Studio: In Visual Studio, on the File menu, click Exit.
10-15
Additional Reading
Restrictions When Overloading Operators
For more information about using the Equals method, see the Object.Equals Method (Object) page at http://go.microsoft.com/fwlink/?LinkId=192954.
10-16
10-17
11-1
Module 11
Decoupling Methods and Handling Events
Contents:
Lesson 1: Declaring and Using Delegates Lesson 2: Using Lambda Expressions Lesson 3: Handling Events Module Review and Takeaways Lab Review Questions and Answers 2 5 8 12 14
11-2
Lesson 1
11-3
Defining a Delegate
Question: Which of the following are valid scopes to define a delegate: the namespace scope, the class scope, or the method scope? Answer: You can define a delegate at either the namespace or the class scope. You cannot define a delegate in a method.
Invoking a Delegate
Question: Why should you always check that a delegate is not null before you invoke it? Answer: If a delegate does not reference any methods, it will return null. If you attempt to invoke a null delegate, your application will throw a NullReferenceException exception.
11-4
Additional Reading
Defining a Delegate
For more information about delegates, see the Delegates (C# Programming Guide) page at http://go.microsoft.com/fwlink/?LinkId=192955.
Invoking a Delegate
For more information about asynchronous programming, see the Asynchronous Programming Overview page at http://go.microsoft.com/fwlink/?LinkId=192956.
11-5
Lesson 2
11-6
11-7
Additional Reading
Defining Lambda Expressions
For more information about lambda expressions, see the Lambda Expressions (C# Programming Guide) page at http://go.microsoft.com/fwlink/?LinkId=192957.
11-8
Lesson 3
Handling Events
Contents:
Question and Answers Detailed Demo Steps Additional Reading 9 10 11
11-9
Defining an Event
Question: What is the result of defining a public event based on a private delegate? Answer: The code will not compile; it is an error for an event to be more visible than the delegate type that it is based on.
Using Events
Question: Can consuming classes raise an event? Answer: No. An event can be raised only by the containing class or a class that inherits from that class.
11-10
7. 8.
9.
10. Open the MainWindow.xaml.cs file, and then review the event handlers for the Click events. 11. Uncomment the code in the button1_Click method that adds an event handler for the Beat event of the beat object. 12. Uncomment the beat_Beat method. This method handles the Beat event by displaying a message box each time that the event is raised. Note the use of the property from the custom event arguments class. 13. Run the application. 14. Click Start. 15. Verify that the application works correctly. Highlight the message boxes when they appear (they should appear every three seconds). 16. Close the application. 17. Close Visual Studio.
11-11
Additional Reading
Defining an Event
For more information about events, see the Events (C# Programming Guide) page at http://go.microsoft.com/fwlink/?LinkId=192958.
Using Events
For more information about how to publish events, see the How to: Publish Events that Conform to .NET Framework Guidelines (C# Programming Guide) page at http://go.microsoft.com/fwlink/?LinkId=192959. For more information about how to hook up events, see the How to: Hook Up Events By Using IntelliSense (C#) page at http://go.microsoft.com/fwlink/?LinkId=192962.
11-12
11-13
11-14
12-1
Module 12
Using Collections and Building Generic Types
Contents:
Lesson 1: Using Collections Lesson 2: Creating and Using Generic Types Lesson 3: Defining Generic Interfaces and Understanding Variance Lesson 4: Using Generic Methods and Delegates Module Review and Takeaways Lab Review Questions and Answers 2 7 11 14 18 19
12-2
Lesson 1
Using Collections
Contents:
Question and Answers Detailed Demo Steps Additional Reading 3 5 6
12-3
12-4
maximum capacity. The SortedList class also enables you to retrieve items from the collection by specifying the key. Using an array, you must use a numeric index to access items in the array.
12-5
10. Uncomment the code that checks whether the personFromCollection field is null and, if it is not null, writes the information to the screen. 11. Uncomment the code that iterates through every item in the people collection. Run the application: On the Debug menu, click Start Without Debugging. 12. When the application pauses, highlight the data that is returned from the collection and displayed on the screen, and then press ENTER. 13. When the application pauses again, highlight that the details of two people are displayed on the screen, and then press ENTER. 14. Close the application. 15. Close Visual Studio: In Visual Studio, on the File menu, click Exit.
12-6
Additional Reading
Common Collection Classes
For more information about the common collection types, see the Commonly Used Collection Types page at http://go.microsoft.com/fwlink/?LinkId=192963.
12-7
Lesson 2
12-8
12-9
5. 6. 7.
10. Uncomment the code that creates a new instance of the Printer class by specifying the ReferenceGuide type and adds three reference guides to the print queue. 11. Uncomment the code that calls the PrintDocuments method on the referenceGuidePrinter object. This calls the method from the Printer class and removes each item from the print queue. 12. Run the application. 13. Close the application. 14. Close Visual Studio.
12-10
Additional Reading
What Are Generic Types?
For more information about generics, see the Generics (C# Programming Guide) page at http://go.microsoft.com/fwlink/?LinkId=192965.
12-11
Lesson 3
12-12
What Is Invariance?
Question: When you define a generic interface, by default, is it invariant, contravariant, or covariant? Answer: By default, generic interfaces are invariant.
12-13
Additional Reading
Defining Generic Interfaces
For more information about generic interfaces, see the Generic Interfaces (C# Programming Guide) page at http://go.microsoft.com/fwlink/?LinkId=192967. For more information about variant generic interfaces, see the Creating Variant Generic Interfaces (C# and Visual Basic) page at http://go.microsoft.com/fwlink/?LinkId=192968.
12-14
Lesson 4
12-15
12-16
Open the Printer.cs file, and then review the Printer class: In Solution Explorer, double-click Printer.cs, and then describe the Printer class. The Printer class is a generic class that takes a single type parameter named DocumentType. The purpose of the class is to represent a printer that is capable of printing a specific type of document.
4. 5. 6. 7.
Uncomment the code that defines the DocumentAddingToQueueDelegate type. Highlight that the delegate includes a type parameter. Uncomment the code that defines the DocumentAddingToQueue event. Highlight that the event uses the generic delegate that you defined in the previous step. Uncomment the OnDocumentAddingToQueue method and explain how this method is used to raise the event. In the AddDocumentToQueue method, uncomment the code that raises the OnDocumentAddingToQueue event and uses the response to determine whether to add the item to the print queue. Open the Program.cs file, and then review the Program class: In Solution Explorer, double-click Program.cs, and then describe the Program class.
8.
9.
Uncomment the code that adds a handler for the OnDocumentAddingToQueue event, and uncomment the handler method. Explain how the handler method displays a message box and returns a value based on the response.
10. Run the application: On the Debug menu, click Start Without Debugging. 11. In the Reference Guide Printing dialog box, click OK. 12. In the Reference Guide Printing dialog box, click Cancel.
12-17
13. In the Reference Guide Printing dialog box, click OK. 14. When the application pauses, verify that only two documents have printed, because you canceled the second document. 15. Close the application. 16. Open the Printer.cs file: In Solution Explorer, double-click Printer.cs. 17. Uncomment the DocumentPrintedEventArgs generic class, and explain how this class inherits from the EventArgs class and exposes a Document property. Explain that this will be used in an event that will notify subscribers that a document has been printed, and provide the document that printed as an argument. 18. Uncomment the code that defines the DocumentPrinted event by using the Action generic delegate. Explain how this event uses an instance of the Printer generic class and an instance of the DocumentPrintedEventArgs generic class as parameters. 19. Uncomment the OnDocumentPrinted method, and explain how this method raises the DocumentPrinted event. 20. In the PrintDocuments method, uncomment the code that calls the OnDocumentPrinted method, and explain how this raises the DocumentPrinted event whenever a document is printed. 21. Open the Program.cs file, and then review the Program class: In Solution Explorer, double-click Program.cs. 22. Uncomment the code that adds a handler for the DocumentPrinted event, and uncomment the handler method. Explain how the handler method displays a message box. 23. Run the application: On the Debug menu, click Start Without Debugging. 24. In the Reference Guide Printing dialog box, click OK. 25. In the Reference Guide Printing dialog box, click Cancel. 26. In the Reference Guide Printing dialog box, click OK. 27. When the application pauses, verify that only two documents printed, because you canceled the second document, and then press ENTER. 28. In the Report Printed dialog box, click OK three times. 29. When the application pauses, verify that only three documents printed. 30. Close the application. 31. Close Visual Studio: In Visual Studio, on the File menu, click Exit.
12-18
How do generic collection classes differ from nongeneric collection classes? Answer: Generic collection classes are strongly typed and therefore prevent run-time cast exceptions; non-generic classes use the object type, so they risk run-time errors.
3.
When would you use a generic type instead of a nongeneric type? Answer: You use generic types when you need to define a wrapper or provide functionality for unrelated and possibly unknown types.
12-19
13-1
Module 13
Building and Enumerating Custom Collection Classes
Contents:
Lesson 1: Implementing a Custom Collection Class Lesson 2: Adding an Enumerator to a Custom Collection Class Module Review and Takeaways Lab Review Questions and Answers 2 6 10 11
13-2
Lesson 1
13-3
13-4
you can hide the method, and applications that refer to your collection by using an interface reference will work correctly. An interface member that is implemented explicitly can still be accessed and should be implemented fully.
13-5
Additional Reading
Generic Collection Interfaces in the .NET Framework
For more information about the ICollection<T> interface, see the ICollection(OfT) Interface page at http://go.microsoft.com/fwlink/?LinkId=192970. For more information about the IList<T> interface, see the IList(OfT) Interface page at http://go.microsoft.com/fwlink/?LinkId=192971. For more information about the IDictionary<TKey, TValue> interface, see the IDictionary(OfTKey, TValue) Interface page at http://go.microsoft.com/fwlink/?LinkId=192972.
13-6
Lesson 2
13-7
13-8
to return items from your collection in the required order. You can then use the property where you would use an enumerator, for example, in a foreach statement.
13-9
Additional Reading
What Is the IEnumerable<T> Interface?
For more information about the IEnumerable<T> interface, see the IEnumerable(OfT) Interface page at http://go.microsoft.com/fwlink/?LinkId=192973.
13-10
13-11
14-1
Module 14
Using LINQ to Query Data
Contents:
Lesson 1: Using the LINQ Extension Methods and Query Operators Lesson 2: Building Dynamic LINQ Queries and Expressions Module Review and Takeaways Lab Review Questions and Answers 2 7 11 12
14-2
Lesson 1
14-3
Filtering Data
Question: What does the result object represent in the following code example?
IEnumerable<Customer> customers { new Customer{ FirstName = new Customer{ FirstName = new Customer{ FirstName = new Customer{ FirstName = new Customer{ FirstName = new Customer{ FirstName = new Customer{ FirstName = }; = new[] "Luka", LastName="Abrus", Age = 41}, "Syed", LastName="Abbas", Age = 23}, "Keith", LastName="Harris", Age = 59}, "David", LastName="Pelton", Age = 25}, "John", LastName="Peoples", Age = 37}, "Toni", LastName="Poe", Age = 29}, "Jeff", LastName="Price", Age = 74}
Answer: The result object represents a reference to an IEnumerable<Customer> object that contains all of the customers that have a last name of Poe.
Ordering Data
Question: Which extension method would you use to sort an array of strings into descending order? Answer: The OrderByDescending extension method.
14-4
new Customer{ FirstName = "John", LastName="Peoples", Age = 23}, new Customer{ FirstName = "Toni", LastName="Poe", Age = 29}, new Customer{ FirstName = "Jeff", LastName="Price", Age = 23} }; var result = customers.Count(cust => cust.LastName.StartsWith("P"));
Answer: The result object contains an enumerable result set that contains a new type that models the make and model of the cell phone, and the network name.
Answer: Yes, both code examples produce the same result of 232.12
14-5
foreach statement. You then make a change to one of the employee records in the database. Finally, you return to the Microsoft Visual Studio debugger and continue to step into the foreach statement. Will the change that you made to the employee record be visible when you iterate through the results? Answer: Yes. The change will be visible because the LINQ query is not evaluated until the foreach statement implicitly invokes the GetEnumerator method.
14-6
Additional Reading
What Is the Purpose of LINQ?
For more information about LINQ, see the Language-Integrated Query (LINQ) page at http://go.microsoft.com/fwlink/?LinkId=192977.
14-7
Lesson 2
14-8
Answer: You can add an extra branch to the tree, as the following diagram shows.
|| / ---------/ / / / && / -------------/ > / / / Member: o.x \ \ \ Constant: 3 / / Member: o.y / \ -------------\ > \ \ \ Constant: 6 / / Member: o.y / \ ---------\ > \ \ \ Constant: 20
14-9
14-10
Additional Reading
What Is an Expression Tree?
For more information about expression trees, see the Expression Trees (C# and Visual Basic) page at http://go.microsoft.com/fwlink/?LinkId=192982.
14-11
14-12
15-1
Module 15
Integrating Visual C# Code with Dynamic Languages and COM Components
Contents:
Lesson 1: Integrating Visual C# Code with Ruby and Python Lesson 2: Accessing COM Components from Visual C# Module Review and Takeaways Lab Review Questions and Answers 2 7 11 12
15-2
Lesson 1
15-3
15-4
Walk through the code. Point out the following items in the Python file: The Customer class, which models a customer. The __init__ method is the constructor. The __str__ method returns a string representation of the customer. The CustomerDB class, which acts as a container for a collection of customers. The __init__ method initializes a list to hold customers. The storeCustomer method adds a customer to the list. The getCustomer method retrieves a customer from the list, and the __str__ method returns the entire list as a formatted string. The GetNewCustomer method, which is a factory method for creating new Customer objects. The GetCustomerDB method, which is a factory method for creating CustomerDB collection objects.
4. 5.
Close the Python file. Start Visual Studio: Click Start, point to All Programs, click Microsoft Visual Studio 2010, and then click Microsoft Visual Studio 2010.
6.
Open the PythonInteroperability solution in the E:\Demofiles\Mod15\PythonInteroperability folder: a. b. On the File menu, point to Open, and then click Project/Solution. Move to the E:\Demofiles\Mod15\PythonInteroperability folder, and then doubleclick PythonInteroperability.sln.
7.
Display the code for the project: In Solution Explorer, expand the PythonInteroperability project, and then double-click Program.cs.
8.
Walk through the code in the Main method. Point out the following items: The CreateRuntime method of the Python class, which is used to create the Python runtime. The UseFile method that references the CustomerDB.py file. The statement that calls the GetNewCustomer method to create a new Python Customer object and store the reference in a variable that is declared as dynamic.
15-5
The statement that calls the GetCustomerDB method to create a new instance of the CustomerDB collection class. The value is returned into a variable that is declared as dynamic. The statement that calls the storeCustomer method to add the Customer object to the CustomerDB collection. The value is stored in a third variable that is declared as dynamic. The statements that call the GetNewCustomer method to create a second customer and the storeCustomer method to add this Customer object to the CustomerDB collection. The Console.WriteLine statement that displays the CustomerDB object. Mention that this statement implicitly calls the ToString method to render the object as a string, which is in turn converted into a call to the __str__ method of the CustomerDB object. 9. Show the references that the solution uses: a. b. In Solution Explorer, expand References. Point out the references to the IronPython and Microsoft.Scripting assemblies, which together provide access to the IronPython runtime.
10. Build and run the application: a. b. c. On the Build menu, click Build Solution. On the Debug menu, click Start Without Debugging. Verify that the application generates the following output: Testing Python Customers ID: 100 Name: Fred ID: 101 Name: Sid 11. Close the console window. 12. Close Visual Studio. Telephone: 888 Telephone: 999
15-6
Additional Reading
What Is the Dynamic Language Runtime?
For more information about the DLR, see the Dynamic Language Runtime Overview page at http://go.microsoft.com/fwlink/?LinkId=192986.
15-7
Lesson 2
15-8
15-9
Additional Reading
Interoperating with COM from a Visual C# Application
For more information about marshaling COM data types, see the COM Data Types page at http://msdn.microsoft.com/en-us/library/sak564ww(v=VS.100).aspx.
15-10
thread that runs an application, you can apply the MTAThread or STAThread attributes to the Main method of the application. Note: If you create an application by using the Windows Application template in Visual Studio, the template tags the Main method with the STAThread attribute. You must not change this attribute, because a Windows graphical user interface (GUI) expects all of the user interaction to occur in a single thread. If you must call COM components that use the MTA model from a Windows application by using a GUI, you should consider creating an additional thread for calling these COM components and then set the ApartmentState property of this thread to ApartmentState.MTA. Cross-apartment marshaling can be expensive and time consuming, so you should try to ensure that managed code calls COM components by using the same apartment. However, this may not always be feasible. If the same managed thread makes calls to STA COM components and MTA COM components, some cross-apartment COM marshaling is unavoidable. As a workaround, you have at least two choices. You could create a new thread for each COM component that you want to use and set its ApartmentState property appropriately (this might prove to be more expensive than performing crossapartment marshaling if you use it to excess). Alternatively, you could try to ensure that the COM components that you use support the Both COM threading model so that they can run in single-threaded and multithreaded apartments.
15-11
15-12
R-1
Resources
Contents:
Microsoft Learning TechNet and MSDN Content Communities 2 3 7
R-2
Microsoft Learning
This section describes various Microsoft Learning programs and offerings. Microsoft Skills Assessments Describes the skills assessment options available through Microsoft Microsoft Learning Describes the training options available through Microsoft face-to-face or self-paced Microsoft Certification Program Details how to become a Microsoft Certified Professional, Microsoft Certified Database Administrators, and more Microsoft Learning Support To provide comments or feedback about the course, send e-mail to support@mscourseware.com To ask about the Microsoft Certification Program (MCP), send e-mail to mcphelp@microsoft.com
R-3
TechNet Content
There is no content from Technet in this course.
MSDN Content
This section includes content from MSDN for this course
Module 1
Microsoft .NET Visual C# What's New in Visual C# 2010 Assemblies in the Common Language Runtime Assembly Versioning Sign Tool (SignTool.exe) .NET Framework Tools Console Class Introduction to Windows Presentation Foundation Video How to: Create a C# WPF Application Control Library XML Documentation Comments (C# Programming Guide) Recommended Tags for Documentation Comments (C# Programming Guide) Main() Command-Line Arguments (C# Programming Guide)
Module 2
C# Keywords General Naming Conventions Capitalization Conventions 3.7 Scopes Convert Class Const (C# Reference) C# Operators Operators (C# Programming Guide) StringBuilder class Harness the Features of C# to Power Your Scientific Computing Projects Single-Dimensional Array (C# Programming Guide) Multidimensional Array (C# Programming Guide) Jagged Array (C# Programming Guide)
R-4
Module 3
Methods (C# Programming Guide) Member Overloading params (C# Reference) Refactoring (C#) Named and Optional Arguments (C# Programming Guide) out parameter modifier (C# Reference)
Module 4
try-catch (C# Reference) Exception Members try-finally (C# Reference) Checked and Unchecked (C# Reference)
Module 5
File Class FileInfo Class Directory Class DirectoryInfo Class Path Class FileStream Class StreamWriter Class StreamReader Class BinaryWriter Class BinaryReader Class
Module 6
Enumeration Types (C# Programming Guide) Instance Constructors (C# Programming Guide) Partial Classes and Methods (C# Programming Guide) ref (C# Reference) Boxing and Unboxing (C# Programming Guide)
Module 7
private (C# Reference)
R-5
public (C# Reference) internal (C# Reference) static (C# Reference) Extension Methods (C# Programming Guide) Classes and Structs (C# Programming Guide)
Module 8
Object Class (System) Polymorphism (C# Programming Guide) Explicit Interface Implementation (C# Programming Guide) Abstract and Sealed Classes and Class Members (C# Programming Guide) abstract (C# Reference) as (C# Reference) is (C# Reference)
Module 9
3.9 Automatic memory management Destructors (C# Programming Guide) GC Members Implementing a Dispose Method using Statement (C# Reference)
Module 10
Properties (C# Programming Guide) Using Properties (C# Programming Guide) Interface Properties (C# Programming Guide) Choosing Between Properties and Methods Comparison Between Properties and Indexers (C# Programming Guide) Using Indexers (C# Programming Guide) Object.Equals Method (Object)
Module 11
Delegates (C# Programming Guide) Asynchronous Programming Overview Lambda Expressions (C# Programming Guide) Events (C# Programming Guide) How to: Publish Events that Conform to .NET Framework Guidelines (C# Programming Guide) How to: Run an Operation in the Background
R-6
Anonymous Methods (C# Programming Guide) How to: Hook Up Events By Using IntelliSense (C#)
Module 12
Commonly Used Collection Types Object and Collection Initializers Generics Constraints on Type Parameters Generic Interfaces Creating Variant Generic Interfaces Covariance and Contravariance in Generics
Module 13
ICollection(T) Interface IList(T) Interface IDictionary(TKey, TValue) Interface IEnumerable (T) Interface IEnumerator (T) Interface Iterators (C# Programming Guide) yield (C# Reference)
Module 14
Language-Integrated Query (LINQ) LINQ Query Expressions (C# Programming Guide) Anonymous Types (C# Programming Guide) LINQ Query Syntax versus Method Syntax (C#) Introduction to LINQ Queries (C#) Expression Trees (C# and Visual Basic) System.Linq.Expressions Namespace Expression Class How to: Use Expression Trees to Build Dynamic Queries
Module 15
Dynamic Language Runtime Overview dynamic (C# Reference) Tlbimp.exe (Type Library Importer)
R-7
Communities
Microsoft Technical Communities Web site.
R-8
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.