Apress Windows 10 Release Sale

Pro C# 2010 and the .NET 4 Platform

5th Edition

By Andrew Troelsen

  • eBook Price: $41.99 $25.19
  • Print Book Price: $59.99
Buy eBook Buy Print Book
Over the years that author Andrew Troelsen has spent working with the common language runtime (CLR), he gained a much deeper understanding of the .NET platform and the subtleties of the C# programming language.

Full Description

  • Add to Wishlist
  • ISBN13: 978-1-4302-2549-2
  • 1752 Pages
  • User Level: Intermediate to Advanced
  • Publication Date: May 13, 2010
  • Available eBook Formats: EPUB, MOBI, PDF

Related Titles

  • Develop on Yammer
  • Pro XAML with C#
  • Extending SSIS with .NET Scripting
  • Pro PowerShell for Database Developers
  • Machine Learning Projects for .NET Developers
Full Description

The first edition of this book was released at the 2001 Tech-Ed conference in Atlanta, Georgia. At that time, the .NET platform was still a beta product, and in many ways, so was this book. This is not to say that the early editions of this text did not have merit—after all, the book was a 2002 Jolt Award finalist and it won the 2003 Referenceware Excellence Award. However, over the years that author Andrew Troelsen spent working with the common language runtime (CLR), he gained a much deeper understanding of the .NET platform and the subtleties of the C# programming language, and he feels that this fifth edition of the book is as close to a “final release” as he’s come yet.

This new edition has been comprehensively revised and rewritten to make it accurately reflect the C# 4 language specification for the .NET 4 platform. You’ll find new chapters covering the important concepts of dynamic lookups, named and optional arguments, Parallel LINQ (PLINQ), improved COM interop, and variance for generics.

If you’re checking out this book for the first time, do understand that it's targeted at experienced software professionals and/or graduate students of computer science (so don't expect three chapters on iteration or decision constructs!). The mission of this text is to provide you with a rock-solid foundation in the C# programming language and the core aspects of the .NET platform (assemblies, remoting, Windows Forms, Web Forms, ADO.NET, XML web services, etc.). Once you digest the information presented in these 25 chapters, you’ll be in a perfect position to apply this knowledge to your specific programming assignments, and you’ll be well equipped to explore the .NET universe on your own terms.

What you’ll learn

  • Be the first to understand the .NET 4 platform and Visual C# 2010.
  • Discover the ins and outs of the leading .NET technology.
  • Learn from an award-winning author who has been teaching the .NET world since version 1.0.
  • Find complete coverage of the WPF, WCF, and WF foundations that support the core .NET platform.

Who this book is for

This book is for anyone with some software development experience who is interested in the new .NET Framework 4 and the C# language. Whether you are moving to .NET for the first time or are already writing applications on .NET 2.0 or .NET 3.5, this book will provide you with a comprehensive grounding in the new technology and serve as a complete reference throughout your coding career.

Table of Contents

Table of Contents

  1. The Philosophy of NET
  2. Building C# Applications
  3. Core C# Programming Constructs, Part I
  4. Core C# Programming Constructs, Part II
  5. Defining Encapsulated Class Types
  6. Understanding Inheritance and Polymorphism
  7. Understanding Structured Exception Handling
  8. Understanding Object Lifetime
  9. Working with Interfaces
  10. Understanding Generics
  11. Delegates, Events, and Lambdas
  12. Advanced C# Language Features
  13. LINQ to Objects
  14. Configuring NET Assemblies
  15. Type Reflection, Late Binding, and Attribute-Based Prog
  16. Processes, AppDomains, and Object Contexts
  17. Understanding CIL and the Role of Dynamic Assemblies
  18. Dynamic Types and the Dynamic Language Runtime
  19. Multithreaded and Parallel Programming
  20. File I/O and Object Serialization
  21. ADO.NET Part I: The Connected Layer
  22. ADO.NET Part II: The Disconnected Layer
  23. ADO.NET Part III: The Entity Framework
  24. Introducing LINQ to XML
  25. Introducing Windows Communication Foundation
  26. Introducing Windows Workflow Foundation 40
  27. Introducing Windows Presentation Foundation and XAML
  28. Programming with WPF Controls
  29. WPF Graphics Rendering Services
  30. WPF Resources, Animations, and Styles
  31. WPF Control Templates and UserControls
  32. Building ASP.NET Web Pages
  33. ASP.NET Web Controls, Master Pages and Theme
  34. ASP.NET State Management Techniques
Source Code/Downloads

Downloads are available to accompany this book.

Your operating system can likely extract zipped downloads automatically, but you may require software such as WinZip for PC, or StuffIt on a Mac.


Please Login to submit errata.

On page 36:

.NET Reflector is recommended here and is said to be used throughout the book, but as of Feb 2011 it has become a paid-for product.

Maybe there is another free decompiler you can recommend for the purposes of the examples in the book :)

On page 88-90:

I think that there is a small mistake or typo in the code snippets of the method:
static void LocalVarDeclerations()
at the very last line which reads Console.WriteLine();

I think this should be Console.ReadLine();

On page 103:

You define the method name as "StringsAreImmutable()" in the first example, then under the Figure (3-11), you define it under the name "StringAreImmutable()". Notice the usage of String as opposed to String(s) in the second example.

On page 105:

A line of code at the top of the page reads
"Console.WriteLine("sb has {0} chars.", sb.Length);"
In the illustration at the bottom of the page, however, this line is printed as "sb as 96 chars.", without the 'h'.

On page 108:

"However, in the case of adding the two shorts within Main(), the end result is completely unacceptable (30,000 + 30,000 = –5536?)."

If 30,000 has a comma in it, then -5536 should also be written as -5,536.

On page 114:

"// OK, is SportsCar is a reference type!

Should be
"//OK, if SportsCar is a reference type!

On page 121:

"For example, the following Main() logic prints a specific string message based on one of two possible
selections (the default case handles an invalid selection)."

The following method is, in fact, ExecuteSwitch(), not Main().

On page 121:
In the note below table 3-8 "C# Logical Operators" it reads "This means once a complex expression has been determined to be false, the remaining expressions will not be checked."

This is incorrect because it only holds for && expressions. In case of a complex || expression, short circuiting will be applied once the first subexpression evaluates to true.

On page 142:

Misprint In the paragraph:

At this point, hopefully you feel comfortable with the process of defining, filling, and examining the contents of a C# array variable. To complete the picture, let's now examine the role of the System.ArraycSystem.Array class.

System.ArraycSystem.Array should be System.Array

On page 191:

In the last paragraph, the text...
"...an array of Shape types could contain..."

appears to must read...
"...an array of Shape-derived types could contain..."

On page 206:
small c# typo on page 206, code fragment below this paragraph:
"Finally, recall that classes can support static constructors. Thus, if you wanted to ensure that the
name of the static companyName field was always assigned to “My Company,” you would write the

// Static constructors are used to initialize static data.
public class Employee
private Static companyName As string
static Employee()
companyName = "My Company";

Static -> static

On page 213:
In the section Calling custom Constructors with Initialization Syntax the code snippet

Point goldPoint = new Point(PointColor.Gold){ X = 90, Y = 20 }
Console.WriteLine("Value of Point is: {0}", goldPoint.DisplayStatus());

,as written, will result in Console.WriteLine trying to pass/ convert a "void" method to an object.

On page 236:

Incorrect variable names in the code:

The book uses the variables "numberOfSales" and "numberOfOptions" when showing how to override the GiveBonus methods.

However, these 2 variables are constructor paramaters for the SalesPerson and Manager classes, and will not be available outside those constructors. Given that the sample code is using automatic properties, thus "hiding" any field names from use within the respective classes, one must use the property names, "SalesNumber" and "StockOptions" when overriding the GiveBonus method.

On page 270:

The comment in the code block is erroneous. The call to the HelpLink property does NOT necessitate creating an Exception object before throwing it. You can use object initializer syntax as follows:

throw Exception ex = new Exception("your message") { HelpLink = "http://www.CarsRUs.com" };

That said, if you are working through the example which DOES require you to create the Exception object before throwing it is invoking the Add method of the Exception's Data property. (This can't be done in object intializer syntax.)

On page 301:

In the only section of non-code/output ("Here, we have purposely...") you state that "the CLR performed a number of them background." which contradicts both the output [as seen on page 302] (of only 1) and my personal output (of only 1). .

On page 347:

ReturnRevesed must be ReturnReversed

On page 381:

In source code, within the try block, the line reads:

Console.WriteLine("\nnFirst Person is: {0}"...

The extra "n" after the new-line escape wasn't intended.

On page 422:

In the example that demonstrates how to register with an event using "+=", the following code for the instantiation of the delegate object is incorrect:

Car.EngineHandler d = new Car.CarEventHandler(CarExplodedEventHandler)

The delegate type for "d" is "Car.EngineHandler" and the delegate type that is being instantiated is "Car.CarEventHandler", so the delegate types do not match. Additionally, assuming that the code in this example was intended to follow the naming conventions of the previous examples, the delegate type should be named "Car.CarEngineHandler".

Additionally, the method name used in the delegate object instantiation - "CarExplodedEventHandler" - should be "CarExploded", as this is the method name that is actually being used later in the same example (on page 423).

The corrected code would be:

Car.CarEngineHandler d = new Car.CarEngineHandler(CarExploded);

On page 429:

In the example at the bottom of the page, the second expression assigning the c1.AboutToBlow EventHandler should have the word "delegate" before the argument list (object sender, CarEventArgs e) but after the += operator.

On page 440, para 2:
Refers to the PeopleCollection in the CustomNonGenericCollection project.

This project is not in the SourceCode/Downloads.
The closest match is in the IssuesWithNonGenericCollections project where there is a PersonCollection (not PeopleCollection)

On page 448:

the section "And What of the += and -+ Operators?"
I believe the "-+" should be "-=".

On page 452:
op_Addition(class OverloadedsOps.Point
This 's' shouldn't be here

On page 604:
The code

MethodInfo mi = sport.GetMethod("TurnOnRadio");

in the method

InvokeMethodWithArgsUsingLateBinding(Assembly asm)

throws an exception

Ambiguous match found.

when the program is run. I am running the program using Windows 7 and Visual C# 2010 Express

On page 676:
Under the section labeled "Defining Member Parameters" you say that the CIL provides a way to define optional parameters "which aren't supported in C# but are used in VB.". This, of course, isn't accurate for a C# 4.0 book as optional parameters are now supported.

On page 749:
The waitHandle. Set(); call should be outside the if conditional. If data is not AddParams, then the application will hang forever

On page 759:
Message does not appear after terminating application:

Press any key to continue . . .

On page 764 - 765:

I have troubles getting the DataParallelismForEach solution to work.
I get the same error, if I write the code from your book, or downloaded the source code and executed that.
Can you confirm there is a bug..?

On this line a exception is thrown: "this.Text = string.Format("Processing {0} on thread {1}", filename, Thread.CurrentThread.ManagedThreadId);"


Cross-thread operation not valid: Control 'MainForm' accessed from a thread other than the thread it was created on.

On page 765:
The following code generates runtime errors due to the following threading issue: "Cross-thread operation not valid: Control 'MainForm' accessed from a thread other than the thread it was created on." The code is: "this.Text = string.Format("Processing {0} on thread {1}", filename,
Thread.CurrentThread.ManagedThreadId);" in the Parallel.ForEach structure. Trying to get it to work using the provided MSDN Help is pretty tricky as well and tends to throw errors or freeze up the program.

On page 812:

Figure 20-5 states: JamesBondCar serialized using a BinaryFormatter. (CarData.dat)

However, the file being shown in this figure is not CarData.dat, but rather the SOAP file CarData.soap.

On page 863:
Check the example provided under the subtopic: Adding the connection logic! Missing the object name of SqlConnection!
Best regards
public class InventoryDAL
// This member will be used by all methods.
private SqlConnection = null; -> MISSING the object sqlCn
public void OpenConnection(string connectionString)
sqlCn = new SqlConnection();
sqlCn.ConnectionString = connectionString;
public void CloseConnection()
Author Comment:

Thank you for your submission. The corrected code should read thusly:

public class InventoryDAL
// This member will be used by all methods.
private SqlConnection sqlCn;
public void OpenConnection(string connectionString)
sqlCn = new SqlConnection();
sqlCn.ConnectionString = connectionString;
public void CloseConnection()

On page 974:
When "Deleting a Record", it says
Car carToDelete = (Car)context.GetObjectByKey(key);
if(carToDelete != null) ...

When using GetObjectByKey, it would throw an error if carToDelete = null.

We should instead use TryGetObjectByKey.

On page 1064 and 1068:

Pg 1064: In the "Enabling MEX" section, the serviceMetadata element needs to have the httpGetUrl attribute set to an absolute URL otherwise a System.InvalidOperationException will occur when attempting to start the Windows Service that hosts the WCF service. For example: httpGetUrl="http://localhost:8080/MathServiceLibrary/mex"

Pg 1068: The Address field in the Add Service Reference dialog box should be set to the same absolute URL as above, i.e.: http://localhost:8080/MathServiceLibrary/mex, otherwise an error will occur attempting to find services at 'http://localhost:8080/MathServiceLibrary

On page 1148:

The SimpleXamlApp.csproj file produces an error when passed to msbuild.exe. I have found the following line
<OutputPath>bin\debug\</OutputPath> needs to be added within the <PropertyGroup> scope for a succesful build:


    1. Pro SQL Server Internals


      View Details

    2. Beginning 3D Game Development with Unity 4


      View Details

    3. Beginning iPhone Development with Swift


      View Details

    4. Financial Modeling for Business Owners and Entrepreneurs


      View Details