Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.
This book has existed, in one form or another, since the first release of C# and the .NET Platform was published in step with Microsoft's release of .NET 1.0 Beta 2 (circa the summer of 2001). Since that point, I have been extremely happy to see that this text continues to be very well received by the press. Over the years, it was nominated as a 2002 Jolt Award finalist (I lost, but hey, life goes on); it was also awarded the 2003 Referenceware Excellence Award for programming book of the year.
More importantly, I have been very grateful to receive e-mails from readers all around the world. It is very cool to chat with so many people who have told me this book has helped their careers in some small way. On a related note, I have to say that this book is better than it has ever been, thanks to the readers who have send me various suggestions for improvements, pointed out typos in the text, and alerted me to other glitches on my part.
I have also been taken aback to learn that this very book has been, and is being used, in college and university settings, and is required reading for numerous undergraduate and graduate courses in the field of computer science.
To the press, readers, and professors, I have nothing to say but thank you and happy programming!
In any case, since the initial release of this book, I have worked hard to keep the material current with each release of the .NET platform. The fifth edition of this text, which you hold in your hands, has been fully updated to provide coverage on the new features of the C# 2010 programming language, as well as the new features of .NET 4.0 Platform. Here you will find information on the new Dynamic Language Runtime (DLR), the Task Parallel Library (TPL), Parallel LINQ (PLINQ), the ADO.NET Entity Framework (EF), and several "minor" (but very useful) updates, such as C# 2010 named arguments, C# 2010 optional parameters, the Lazy<T> class type, and so on.
In addition to covering all the new bits, this book continues to provide you with a rock-solid foundation of the C# language as a whole, the pillars of object oriented programming (OOP), assembly configuration, database access (through ADO.NET), as well as the process of building desktop GUI applications, web applications, and distributed systems (among other topics).
As with the earlier editions, this edition presents the C# programming language and .NET base class libraries using a friendly and approachable tone (or so I have been told!). As well, this new edition remains focused on providing you with the information you need to build software solutions today, rather than spending too much time examining esoteric details that few individuals will ever actually care about.
Technology authors write for a demanding group of people (I should know—I'm one of them). You know that building software solutions using any platform (e.g., .NET, Java, and COM) is extremely complicated and is highly specific to your department, company, client base, and subject matter. Perhaps you work in the electronic publishing industry, develop systems for the state or local government, or work at NASA or a branch of the military. Speaking for myself, I have developed children's educational software (Oregon Trail / Amazon Trail anyone?), various n-tier systems, and projects within the medical and financial industries. The chances are almost 100 percent that the code you write at your place of employment has little to do with the code I write at mine (unless we happened to work together previously!).
Therefore, in this book, I have deliberately chosen to avoid creating examples that tie the example code to a specific industry or vein of programming. Given this, I explain C#, OOP, the CLR, and the .NET 4.0 base class libraries using industry-agnostic examples. Rather than having every blessed example fill a grid with data, calculate payroll, or whatnot, I'll stick to subject matter everyone can relate to: automobiles (with some geometric structures and employee payroll systems thrown in for good measure). And that's where you come in.
My job is to explain the C# programming language and the core aspects of the .NET platform as well as I possibly can. I will also do everything I can to equip you with the tools and strategies you need to continue your studies at this book's conclusion.
Your job is to take this information and apply it to your specific programming assignments. I obviously appreciate that your projects most likely don't revolve around automobiles with friendly pet names (e.g., Zippy the BMW and a Yugo named Clunker), but that's what applied knowledge is all about!
Rest assured, once you understand the topics and concepts presented within this text, you will be in a perfect position to build .NET solutions that map to your own unique programming environment.
Pro C# 2010 and the .NET 4.0 Platform, Fifth Edition is logically divided into seven distinct parts, each of which contains a number of related chapters. If you have read the earlier editions of this text, you will quickly notice a number of changes. For example, I am no longer isolating new C# language features to a dedicated chapter. Rather, they are included as part of a specific chapter where they can be introduced naturally. Furthermore, based on reader feedback, I have greatly expanded my coverage of Windows Presentation Foundation (WPF). Here is a part-by-part and chapter-by-chapter breakdown of the text.
The purpose of Part 1 is to acclimate you to the nature of the .NET platform and various development tools (many of which are open source) used during the construction of .NET applications. Along the way, you will also check out some fundamental details of the C# programming language and the .NET type system.
This first chapter functions as the backbone for the remainder of the text. You begin by examining the world of traditional Windows development and uncover the shortcomings with the previous state of affairs. The primary goal of this chapter, however, is to acquaint you with a number of .NET centric building blocks, such as the Common Language Runtime (CLR), Common Type System (CTS), Common Language Specification (CLS), and base class libraries. Here, you will take an initial look at the C# programming language and the .NET assembly format; you will also get an overview of the platform-independent nature of the .NET platform (Appendix B will examine this topic in greater detail).
The goal of this chapter is to introduce you to the process of compiling C# source code files using various tools and techniques. You will begin by learning how to use the command-line compiler (csc.exe) and C# response files. Over the remainder of the chapter, you will examine numerous code editors and integrated development environments (IDEs), including Notepad++, SharpDevelop, Visual C# 2010 Express, and Visual Studio 2010. You will also learn how to configure your development machine with a local installation of the all important .NET Framework 4.0 SDK documentation.
The topics presented in this part of the book are quite important because you will use them regardless of which type of .NET software you intend to develop (e.g., web applications, desktop GUI applications, code libraries, and Windows services). Here, you will come to understand the core constructs of the C# language, including the details of object-oriented programming (OOP). This part will also examine how to process runtime exceptions and dive into the details of .NET's garbage collection services.
This chapter begins your formal investigation of the C# programming language. Here you will learn about the role of the Main() method and numerous details regarding the intrinsic data types of the .NET platform, including the manipulation of textual data using System.String and System.Text.StringBuilder. You will also examine iteration and decision constructs, narrowing and widening operations, and the unchecked keyword.
This chapter completes your examination of the core aspects of C#, beginning with the construction of overloaded type methods and defining parameters using the out, ref, and params keywords. This chapter will examine two new C# 2010 features called arguments and optional parameters. You will also learn how to create and manipulate arrays of data, define nullable data types (with the ? and ?? operators), and understand the distinction between value types (including enumerations and custom structures) and reference types.
This chapter begins your examination of object-oriented programming (OOP) using the C# programming language. Once you master the pillars of OOP (encapsulation, inheritance, and polymorphism), the remainder of this chapter will show you how to build robust class types using constructors, properties, static members, constants, and read-only fields. You will wrap up with an examination of partial type definitions, object initialization syntax, and automatic properties.
Here, you will examine the remaining pillars of OOP (inheritance and polymorphism), which allow you to build families of related class types. As you do this, you will examine the role of virtual methods, abstract methods (and abstract base classes), and the nature of the polymorphic interface. Last but not least, this chapter will explain the role of the supreme base class of the .NET platform, System.Object.
The point of this chapter is to discuss how to handle runtime anomalies in your code base through the use of structured exception handling. Not only will you learn about the C# keywords that allow you to handle such problems (try, catch, throw, and finally), but you will also come to understand the distinction between application-level and system-level exceptions. In addition, this chapter will examine various tools within Visual Studio 2010 that allow you to debug the exceptions that escape your notice.
The final chapter of this part examines how the CLR manages memory using the .NET garbage collector. Here you will come to understand the role of application roots, object generations, and the System.GC type. Once you understand the basics, you will examine the topics of disposable objects (using the IDisposable interface) and the finalization process (using the System.Object.Finalize() method). This chapter will also investigate a new .NET 4.0 class, Lazy<T>, which allows you to define data that will not be allocated until requested by a caller. As you will see, this feature can be very helpful when you wish to ensure you do not clutter the heap with objects that are not actually required by your programs.
This section of the book will deepen your understanding of the C# language by walking you through a number of more advanced (but very important) concepts. Here, you will complete your examination of the .NET type system by examining interfaces and delegates. You will also learn about the role of generics, take a first look at Language Integrated Query (LINQ), and examine a number of more advanced features of C# (e.g., extension methods, partial methods, and pointer manipulation).
The material in this chapter builds upon your understanding of object-based development by covering the topic of interface-based programming. Here, you will learn how to define classes and structures that support multiple behaviors, how to discover these behaviors at runtime, and how to selectively hide particular behaviors using explicit interface implementation. In addition to creating a number of custom interfaces, you will also learn how to implement standard interfaces found within the .NET platform. You will use these to build objects that can be sorted, copied, enumerated and compared.
This chapter explores the topic of generics. As you will see, generic programming gives you a way to create types and type members, which contain various placeholders that can be specified by the caller. In a nutshell, generics greatly enhance application performance and type safety. Not only will you explore various generic types within the System.Collections.Generic namespace, but you will also learn how to build your own generic methods and types (with and without constraints).
The purpose of Chapter 11 is to demystify the delegate type. Simply put, a .NET delegate is an object that points to other methods in your application. Using this type, you can build systems that allow multiple objects to engage in a two-way conversation. After you have examined the use of .NET delegates, you will then be introduced to the C# event keyword, which you can use to simplify the manipulation of raw delegate programming. You will wrap up this chapter by investigating the role of the C# lambda operator (=>) and exploring the connection between delegates, anonymous methods, and lambda expressions.
This chapter deepens your understanding of the C# programming language by introducing you to a number of advanced programming techniques. Here, you will learn how to overload operators and create custom conversion routines (both implicit and explicit) for your types. You will also learn how to build and interact with type indexers, as well as work with extension methods, anonymous types, partial methods, and C# pointers using an unsafe code context.
This chapter will begin your examination of Language Integrated Query (LINQ). LINQ allows you to build strongly typed query expressions that can be applied to a number of LINQ targets to manipulate data in the broadest sense of the word. Here, you will learn about LINQ to Objects, which allows you to apply LINQ expressions to containers of data (e.g., arrays, collections, and custom types). This information will serve you well as you encounter a number of additional LINQ APIs throughout the remainder of this book (e.g., LINQ to XML, LINQ to DataSet, PLINQ, and LINQ to Entities).
Part 4 dives into the details of the .NET assembly format. Not only will you learn how to deploy and configure .NET code libraries, but you will also come to understand the internal composition of a .NET binary image. This part also explains the role of .NET attributes and the role of resolving type information at runtime. This section will also explain the role of the .NET 4.0 Dynamic Language Runtime (DLR) and the C# 2010 dynamic keyword. Later chapters will examine some fairly advanced topics, such as object context, CIL code, and the construction of in-memory assemblies.
At a very high level, assembly is the term used to describe a *.dll or *.exe binary file created with a .NET compiler. However, the true story of .NET assemblies is far richer than that. Here you will learn the distinction between single-file and multifile assemblies, as well as how to build and deploy each entity. You'll also examine how you can configure private and shared assemblies using XML-based *.config files and publisher policy assemblies. Along the way, you will investigate the internal structure of the global assembly cache (GAC), including some changes to the GAC as of .NET 4.0.
Chapter 15 continues your examination of .NET assemblies by checking out the process of runtime type discovery using the System.Reflection namespace. Using the types of this namespace, you can build applications that can read an assembly's metadata on the fly. You will also learn how to load and create types at runtime dynamically using late binding. The final topic of this chapter will explore the role of .NET attributes (both standard and custom). To illustrate the usefulness of each of these topics, the chapter shows you how to construct an extendable Windows Forms application.
Now that you have a solid understanding of assemblies, this chapter dives deeper into the composition of a loaded .NET executable. The goal of this chapter is to illustrate the relationship between processes, application domains, and contextual boundaries. These topics provide the proper foundation for Chapter 19, where you will examine the construction of multithreaded applications.
The goal of this chapter is twofold. In the first half (more or less), you will examine the syntax and semantics of CIL in much greater detail than in previous chapters. The remainder of this chapter will cover the role of the System.Reflection.Emit namespace. You can use these types to build software that can generate .NET assemblies in memory at runtime. Formally speaking, assemblies defined and executed in memory are termed dynamic assemblies. You should not confuse this term with a dynamic type, which is the subject of Chapter 18.
.NET 4.0 introduces a new aspect of the .NET runtime environment called the dynamic language runtime. Using the DLR and the C# 2010 dynamic keyword, you can define data that is not truly resolved until runtime. Using these features simplifies some very complex .NET programming tasks dramatically. In this chapter, you will learn some practical uses of dynamic data, including how to leverage the .NET reflection APIs in a streamlined manner, as well as how to communicate with legacy COM libraries a minimum of fuss and bother.
By this point in the text, you have a solid handle on the C# language and the details of the .NET assembly format. Part 5 leverages your newfound knowledge by exploring a number of commonly used services found within the base class libraries, including the creation of multithreaded application, file I/O, and database access using ADO.NET. This part also covers the construction of distributed applications using Windows Communication Foundation (WCF), workflow-enabled applications that use the Windows Workflow Foundation (WF) API and the LINQ to XML API.
This chapter examines how to build multithreaded applications and illustrates a number of techniques you can use to author thread-safe code. The chapter opens by revisiting the .NET delegate type to ensure, explaining a delegate's intrinsic support for asynchronous method invocations. Next, you will investigate the types within the System.Threading namespace. The remainder of this chapter covers a brand new .NET 4.0 API called the Task Parallel Library (TPL). Using the TPL, .NET developers can build applications that distribute their workload across all available CPUs in a wickedly simple manner. At this point, you will also learn about the role of Parallel LINQ (PINQ), which provides a way to create LINQ queries that scale across multiple machine cores.
The System.IO namespace allows you to interact with a machine's file and directory structure. Over the course of this chapter, you will learn how to create (and destroy) a directory system programmatically. You will also learn how to move data into and out of various streams (e.g., file based, string based, and memory based). The latter part of this chapter will examine the object serialization services of the .NET platform. Simply put, serialization allows you to persist the state of an object (or a set of related objects) into a stream for later use. Deserialization (as you might expect) is the process of plucking an object from the stream into memory for consumption by your application. Once you understand the basics, you will learn how to customize the serialization process using the ISerializable interface and a set of .NET attributes.
In this first of three database-centric chapters, you will take your first look at the database access API of the .NET platform, ADO.NET. Specifically, this chapter will introduce you to the role of .NET data providers and how to communicate with a relational database using the connected layer of ADO.NET, which is represented by connection objects, command objects, transaction objects, and data reader objects. Be aware that this chapter will also walk you through the creation of a custom database and the first iteration of a custom data access library (AutoLotDAL.dll); you will use this library throughout the remainder of this book.
This chapter continues your study of database manipulation by examining the disconnected layer of ADO.NET. Here, you will learn the role of the DataSet type, data adapter objects. You will also learn about the many tools of Visual Studio 2010 that can greatly simplify the creation of data-driven applications. Along the way, you will learn how to bind DataTable objects to user interface elements, as well as how to apply LINQ queries to in-memory DataSet objects using LINQ to DataSet.
This chapter wraps up your investigation of ADO.NET by examining the role of the Entity Framework (EF). Essentially, EF is a way for you to author data access code using strongly typed classes that directly map to your business model. Here, you will come to understand the role of EF Object Services, the Entity Client and Object Context, and the composition of an *.edmx file. While doing so, you will learn to interact with relational databases using LINQ to Entities. You will also build the final version of your custom data access library (AutoLotDAL.dll), which you will use in several of the remaining chapters of the book.
Chapter 14 introduced you to the core LINQ programming model—specifically LINQ to Objects. Here, you will deepen your understanding of Language Integrated Query by examining how to apply LINQ queries to XML documents. You will begin by learning about the "warts" that were present in .NET's initial foray into XML manipulation as you use the types of the System.Xml.dll assembly. With this brief history lesson behind you, you will explore how to create XML documents in memory, how to persist them to the hard drive, and how to navigate their contents using the LINQ programming model (LINQ to XML).
Until this point in the book, all of the sample applications have executed on a single computer. In this chapter, you will learn about the Windows Communication Foundation (WCF) API that allows you to build distributed applications in a symmetrical manner, regardless of their underlying plumbing. This chapter will expose you to the construction of WCF services, hosts, and clients. As you will see, WCF services are extremely flexible because they allow clients and hosts to leverage XML-based configuration files to specify addresses, bindings, and contracts declaratively. This chapter will also showcase a number of helpful shortcuts that introduced in .NET 4.0.
Of all the .NET APIs, Windows Workflow Foundation (WF) can provide the biggest source of confusion for new developers. In fact, with the release of .NET 4.0, the initial incarnation of the WF API (introduced in .NET 3.0) has been given a complete, and total, reboot. In this chapter, you will begin by learning about the role of a workflow-enabled application, and you will come to understand the various ways to model business processes using the .NET 4.0 WF API. Next, you will examine the scope of the WF 4.0 activity library, as well as learn how to build custom activities that will use the custom database access library you created earlier in the book.
.NET 3.0 introduced programmers to an amazing API called Windows Presentation Foundation (WFP). This API has quickly become the heir apparent to the Windows Forms desktop programming model. In essence, WPF allows you to build desktop applications that incorporate vector graphics, interactive animations, and data-binding operations using a declarative markup grammar called XAML. Furthermore, the WPF control architecture provides a trivial way to restyle the look-and-feel of a typical control radically using little more than some well-formed XAML. I am happy to say that this edition of the text includes five chapters dedicated to the WPF programming model.
Essentially, WPF allows you to build extremely interactive and media-rich front ends for desktop applications (and indirectly, web applications). Unlike Windows Forms, this supercharged UI framework integrates a number of key services (e.g., 2D and 3D graphics, animations, and rich documents) into a single, unified object model. In this chapter, you will begin your examination of WPF and the Extendable Application Markup Language (XAML). Here, you will learn how to build WPF programs without XAML, using nothing but XAML, and by using a combination of both approaches. You will wrap up the chapter by building a custom XAML editor that you will use for the remainder of the WPF-centric chapters.
This chapter will expose you to the process of using intrinsic WPF controls and layout managers. For example, you will learn to build menu systems, splitter windows, toolbars, and status bars. This chapter will also introduce you to a number of WPF APIs (and their related controls), including the WPF Documents API, the WPF Ink API, and the data-binding model. Just as importantly, this chapter will begin your investigation of Expression Blend IDE, which simplifies the task of creating rich UIs for a WPF application.
WPF is a graphically intensive API; given this fact, WPF provides three ways to render graphics: shapes, drawings and geometrics, and visuals. In this chapter, you will evaluate each option and learn about a number of important graphics primitives (e.g., brushes, pens, and transformations) along the way. This chapter will also examine a number of ways in which Expression Blend can help you simplify the process of creating WPF graphics, as well as how to perform hit-testing operations against graphical data.
This chapter will introduce you to three important (and interrelated) topics that will deepen your understanding of the Windows Presentation Foundation API. The first order of business is to learn the role of logical resources. As you will see, the logical resource (also termed an object resource) system provides a way for you to name and refer to commonly used objects within a WPF application. Next, you will learn how to define, execute, and control an animation sequence. Despite what you might be thinking, however, WPF animations are not limited to the confines of video game or multimedia applications. You will wrap up the chapter by learning about the role of WPF styles. Similar to a web page that uses CSS or the ASP.NET theme engine, a WPF application can define a common look-and-feel for a set of controls.
This chapter concludes your investigation of the WPF programming model by introducing you to the process of building customized controls. This chapter begins by examining two topics that are important when creating a custom control: dependency properties and routed events. Once you understand these topics, you will learn about the role of a default template, as well as how to view them programmatically at runtime. Once this foundation has been laid, the remainder of this chapter will examine how to build custom UserControl classes using Visual Studio 2010 and Expression Blend, including the .NET 4.0 Visual State Manager (VSM).
Part 7 is devoted to an examination of constructing web applications using the ASP.NET programming API. Microsoft designed ASP.NET to model the creation of desktop user interfaces by layering an event-driven, object-oriented framework on top of a standard HTTP request/response.
This chapter begins your study of web application development using ASP.NET. As you will see, server-side scripting code has now been replaced with real object-oriented languages (e.g., C# and VB .NET). This chapter will examine the construction of an ASP.NET web page, the underlying programming model, and other key aspects of ASP.NET, such as your choice of web server and the use of Web.config files.
Whereas the previous chapter showed you how to construct ASP.NET Page objects, this chapter will examine the controls that populate the internal control tree. Here, you will examine the core ASP.NET web controls, including validation controls, the intrinsic site navigation controls, and various data-binding operations. This chapter will also illustrate the role of master pages and the ASP.NET theme engine, which is a server-side alternative to traditional style sheets.
This chapter extends your understanding of ASP.NET by examining various ways to handle state management under .NET. Like classic ASP, ASP.NET allows you to create cookies and application-level and session-level variables quite easily. However, ASP.NET also introduces a new state management technique: the application cache. Once you look at the numerous ways to handle state with ASP.NET, you will examine the role of the HttpApplication base class and learn how to alter the runtime behavior of your web application dynamically using the Web.config file.
This final part of this book examines two important topics that did not seem to fit naturally within the bulk of the text, so I have placed them in appendices. Here you will complete your examination of C# and the .NET platform by gaining an overview of the initial GUI framework of the .NET platform (Windows Forms). You will also learn how to use the Mono Platform to build .NET applications on operating systems beyond Microsoft Windows.
The original desktop GUI toolkit that shipped with the .NET platform is called Windows Forms. This appendix will walk you through the role of this UI framework and illustrate how to build main windows, dialog boxes, and menu systems. You will also learn about the role of form inheritance and see how to render 2D graphical data using the System.Drawing namespace. You will wrap things up by building a (semi-capable) painting application that illustrates the various topics discussed throughout this appendix.
Last but not least, Appendix B covers how to use an open source implementation of the .NET platform named Mono. You can use Mono to build feature-rich .NET applications that can be created, deployed, and executed upon a variety of operating systems, including Mac OS X, Solaris, AIX, and numerous other Linux distributions. Given that Mono is largely comparable with Microsoft's .NET platform, you already know most of what Mono has to offer. Therefore, this appendix will focus on the Mono installation process, Mono development tools, and Mono runtime engine.
You can find all of the code examples contained in this book available as a free download from the Source Code/Download area of the Apress website. Simply navigate to www.apress.com, select the Source Code/Download link, and look up this title by name. Once you are on the home page for Pro C# 2010 and the .NET 4.0 Platform, Fifth Edition, you can download a self-extracting *.zip file. After you unzip the contents, you will find that the code has been partitioned on a chapter-by-chapter basis.
On a related note, be aware that you will find Source Code notes such as the following in many of the book's chapters. These notes serves as your visual cue that you can load the example under discussion into Visual Studio 2010 for further examination and modification:
NOTE
This is a source code note that refers you to a specific directory in the ZIP archive!
To open a solution into Visual Studio 2010, use the File Open Project/Solution menu option, and then navigate to the correct *.sln file within the correct subdirectory of the unzipped archive.
As you read through this text, you might find an occasional grammatical or code error (although I sure hope not). If this is the case, please accept my apologies. Being human, I am sure that a glitch or two might be present, despite my best efforts. If this is the case, you can obtain the current errata list from the Apress website (again, this is located on the home page for this book), as well as information on how to notify me of any errors you might find.
If you have any questions regarding this book's source code, are in need of clarification for a given example, or simply wish to offer your thoughts regarding the .NET platform, feel free to drop me a line at the following email address (to ensure your messages don't end up in my junk mail folder, please include "C# FifthEd" in the Subject line somewhere):
atroelsen@intertech.com
Please understand that I will do my best to get back to you in a timely fashion; however, like yourself, I get busy from time to time. If I don't respond within a week or two, please be aware that I am not trying to be a jerk, nor am I trying to avoid talking to you. I'm just busy (or, if I'm lucky, on vacation somewhere). So, then! Thanks for buying this text (or at least looking at it in the bookstore while you try to decide whether you will buy it). I hope you enjoy reading this book and putting your newfound knowledge to good use.
Take care,
Andrew Troelsen