Home > Store

C# 4.0 How-To

Register your product to gain access to bonus material or receive a coupon.

C# 4.0 How-To


  • Sorry, this book is no longer in print.
Not for Sale

eBook (Watermarked)

  • Your Price: $30.39
  • List Price: $37.99
  • Includes EPUB and PDF
  • About eBook Formats
  • This eBook includes the following formats, accessible from your Account page after purchase:

    ePub EPUB The open industry format known for its reflowable content and usability on supported mobile devices.

    Adobe Reader PDF The popular standard, used most often with the free Acrobat® Reader® software.

    This eBook requires no passwords or activation to read. We customize your eBook by discreetly watermarking it with your name, making it uniquely yours.


  • Copyright 2010
  • Edition: 1st
  • Book
  • ISBN-10: 0-672-33063-6
  • ISBN-13: 978-0-672-33063-6

Real Solutions for C# 4.0 Programmers

Need fast, robust, efficient code solutions for Microsoft C# 4.0? This book delivers exactly what you’re looking for. You’ll find more than 200 solutions, best-practice techniques, and tested code samples for everything from classes to exceptions, networking to XML, LINQ to Silverlight. Completely up-to-date, this book fully reflects major language enhancements introduced with the new C# 4.0 and .NET 4.0. When time is of the essence, turn here first: Get answers you can trust and code you can use, right now!

Beginning with the language essentials and moving on to solving common problems using the .NET Framework, C# 4.0 How-To addresses a wide range of general programming problems and algorithms. Along the way is clear, concise coverage of a broad spectrum of C# techniques that will help developers of all levels become more proficient with C# and the most popular .NET tools.

Fast, Reliable, and Easy to Use!

  • Write more elegant, efficient, and reusable code
  • Take advantage of real-world tips and best-practices advice
  • Create more effective classes, interfaces, and types
  • Master powerful data handling techniques using collections, serialization, databases, and XML
  • Implement more effective user interfaces with both WPF and WinForms
  • Construct Web-based and media-rich applications with ASP.NET and Silverlight
  • Make the most of delegates, events, and anonymous methods
  • Leverage advanced C# features ranging from reflection to asynchronous programming
  • Harness the power of regular expressions
  • Interact effectively with Windows and underlying hardware
  • Master the best reusable patterns for designing complex programs



Download the example code

Sample Content

Online Sample Chapter

C# 4.0 How-To: Creating Versatile Types

Sample Pages

Download the sample pages (includes Chapter 2 and Index)

Table of Contents

Introduction     1

Overview of C# 4.0 How-To     1

How-To Benefit from This Book     1

How-To Continue Expanding Your Knowledge     3


Chapter 1   Type Fundamentals     7

Create a Class     8

Define Fields, Properties, and Methods     9

Define Static Members     10

Add a Constructor      11

Initialize Properties at Construction     12

Use const and readonly     13

Reuse Code in Multiple Constructors     14

Derive from a Class    14

Call a Base Class Constructor     15

Override a Base Class’s Method or Property     16

Create an Interface     19

Implement Interfaces     19

Create a Struct     21

Create an Anonymous Type     22

Prevent Instantiation with an Abstract Base Class     23

Interface or Abstract Base Class?     24

Chapter 2   Creating Versatile Types     27

Format a Type with ToString()     28

Make Types Equatable.    32

Make Types Hashable with GetHashCode()     34

Make Types Sortable     34

Give Types an Index     36

Notify Clients when Changes Happen     38

Overload Appropriate Operators     39

Convert One Type to Another     40

Prevent Inheritance      41

Allow Value Type to Be Null     42

Chapter 3   General Coding     45

Declare Variables     46

Defer Type Checking to Runtime (Dynamic Types)     47

Use Dynamic Typing to Simplify COM Interop     49

Declare Arrays     50

Create Multidimensional Arrays     50

Alias a Namespace     51

Use the Conditional Operator (?:)     52

Use the Null-Coalescing Operator (??)     53

Add Methods to Existing Types with Extension Methods     54

Call Methods with Default Parameters     55

Call Methods with Named Parameters     56

Defer Evaluation of a Value Until Referenced     57

Enforce Code Contracts     58

Chapter 4   Exceptions     63

Throw an Exception     64

Catch an Exception     64

Catch Multiple Exceptions     65

Rethrow an Exception     66

(Almost) Guarantee Execution with finally     67

Get Useful Information from an Exception     68

Create Your Own Exception Class     70

Catch Unhandled Exceptions     72

Usage Guidelines     76

Chapter 5   Numbers     77

Decide Between Float, Double, and Decimal     78

Use Enormous Integers (BigInteger)     79

Use Complex Numbers     80

Format Numbers in a String     82

Convert a String to a Number     86

Convert Between Number Bases     87

Convert a Number to Bytes (and Vice Versa)     89

Determine if an Integer Is Even     91

Determine if an Integer Is a Power of 2 (aka, A Single Bit Is Set)      91

Determine if a Number Is Prime     91

Count the Number of 1 Bits     92

Convert Degrees and Radians     93

Round Numbers     93

Generate Better Random Numbers     96

Generate Unique IDs (GUIDs)     97

Chapter 6   Enumerations     99

Declare an Enumeration     100

Declare Flags as an Enumeration     101

Determine if a Flag Is Set     102

Convert an Enumeration to an Integer (and Vice Versa)     102

Determine if an Enumeration Is Valid     103

List Enumeration Values     103

Convert a String to an Enumeration     103

Attach Metadata to Enums with Extension Methods     104

Enumeration Tips     106

Chapter 7   Strings     109

Convert a String to Bytes (and Vice Versa)     110

Create a Custom Encoding Scheme     111

Compare Strings Correctly     115

Change Case Correctly     116

Detect Empty Strings     117

Concatenate Strings: Should You Use StringBuilder?     117

Concatenate Collection Items into a String     119

Append a Newline Character    120

Split a String     121

Convert Binary Data to a String (Base-64 Encoding)     122

Reverse Words     124

Sort Number Strings Naturally     125

Chapter 8   Regular Expressions     131

Search Text     132

Extract Groups of Text     132

Replace Text     133

Match and Validate     134

Help Regular Expressions Perform Better     137

Chapter 9   Generics     139

Create a Generic List     140

Create a Generic Method      141

Create a Generic Interface     142

Create a Generic Class      143

Create a Generic Delegate     145

Use Multiple Generic Types.     146

Constrain the Generic Type     146

Convert IEnumerable<string> to IEnumerable<object> (Covariance)     149

Convert IComparer<Child> to IComparer<Parent> (Contravariance)     150

Create Tuples (Pairs and More)     151


Chapter 10  Collections     155

Pick the Correct Collection Class     156

Initialize a Collection     157

Iterate over a Collection Independently of Its Implementation     158

Create a Custom Collection     159

Create Custom Iterators for a Collection     163

Reverse an Array     166

Reverse a Linked List     167

Get the Unique Elements from a Collection     168

Count the Number of Times an Item Appears     168

Implement a Priority Queue     169

Create a Trie (Prefix Tree)     173

Chapter 11  Files and Serialization     177

Create, Read, and Write Files     178

Delete a File     180

Combine Streams (Compress a File)     181

Get a File Size     183

Get File Security Description     183

Check for File and Directory Existence     185

Enumerate Drives     185

Enumerate Directories and Files     186

Browse for Directories     187

Search for a File or Directory     188

Manipulate File Paths     190

Create Unique or Temporary Filenames     192

Watch for File System Changes     192

Get the Paths to My Documents, My Pictures, Etc.     194

Serialize Objects     194

Serialize to an In-Memory Stream     198

Store Data when Your App Has Restricted Permissions     198

Chapter 12  Networking and the Web     201

Resolve a Hostname to an IP Address     202

Get This Machine’s Hostname and IP Address     202

Ping a Machine     203

Get Network Card Information     204

Create a TCP/IP Client and Server     204

Send an Email via SMTP     208

Download Web Content via HTTP     209

Upload a File with FTP     213

Strip HTML of Tags     214

Embed a Web Browser in Your Application     214

Consume an RSS Feed     216

Produce an RSS Feed Dynamically in IIS     220

Communicate Between Processes on the Same Machine (WCF)     222

Communicate Between Two Machines on the Same Network (WCF)     229

Communicate over the Internet (WCF)     231

Discover Services During Runtime (WCF)     233

Chapter 13  Databases     237

Create a New Database from Visual Studio     238

Connect and Retrieve Data     240

Insert Data into a Database Table     245

Delete Data from a Table     246

Run a Stored Procedure     247

Use Transactions     248

Bind Data to a Control Using a DataSet     250

Detect if Database Connection Is Available     258

Automatically Map Data to Objects with the Entity Framework     259

Chapter 14  XML     261

Serialize an Object to and from XML     262

Write XML from Scratch     266

Read an XML File     268

Validate an XML Document     270

Query XML Using XPath     271

Transform Database Data to XML     273

Transform XML to HTML     274


Chapter 15  Delegates, Events, and Anonymous Methods     279

Decide Which Method to Call at Runtime      280

Subscribe to an Event     282

Publish an Event     283

Ensure UI Updates Occur on UI Thread     285

Assign an Anonymous Method to a Delegate     288

Use Anonymous Methods as Quick-and-Easy Event Handlers     288

Take Advantage of Contravariance     291

Chapter 16  Windows Forms     295

Create Modal and Modeless Forms     296

Add a Menu Bar     297

Disable Menu Items Dynamically     300

Add a Status Bar     300

Add a Toolbar     301

Create a Split Window Interface     302

Inherit a Form     304

Create a User Control     308

Use a Timer     313

Use Application and User Configuration Values     314

Use ListView Efficiently in Virtual Mode     317

Take Advantage of Horizontal Wheel Tilt     319

Cut and Paste     323

Automatically Ensure You Reset the Wait Cursor     327

Chapter 17  Graphics with Windows Forms and GDI+     329

Understand Colors     330

Use the System Color Picker     330

Convert Colors Between RGB to HSV     331

Draw Shapes     335

Create Pens.     337

Create Custom Brushes     339

Use Transformations     341

Draw Text     344

Draw Text Diagonally     344

Draw Images     344

Draw Transparent Images     345

Draw to an Off-Screen Buffer     346

Access a Bitmap’s Pixels Directly for Performance     347

Draw with Anti-Aliasing     348

Draw Flicker-Free     349

Resize an Image     350

Create a Thumbnail of an Image     351

Take a Multiscreen Capture     352

Get the Distance from the Mouse Cursor to a Point     354

Determine if a Point Is Inside a Rectangle     355

Determine if a Point Is Inside a Circle     355

Determine if a Point Is Inside an Ellipse     356

Determine if Two Rectangles Intersect.     357

Print and Print Preview     358

Chapter 18  WPF     365

Show a Window     366

Choose a Layout Method     367

Add a Menu Bar     367

Add a Status Bar     369

Add a Toolbar     369

Use Standard Commands     370

Use Custom Commands     371

Enable and Disable Commands     374

Expand and Collapse a Group of Controls     375

Respond to Events     376

Separate Look from Functionality     377

Use Triggers to Change Styles at Runtime     378

Bind Control Properties to Another Object     379

Format Values During Data Binding     383

Convert Values to a Different Type During Data Binding     383

Bind to a Collection     385

Specify How Bound Data Is Displayed     385

Define the Look of Controls with Templates     386

Animate Element Properties     388

Render 3D Geometry     389

Put Video on a 3D Surface     392

Put Interactive Controls onto a 3D Surface     395

Use WPF in a WinForms App     398

Use WinForms in a WPF Application     400

Chapter 19  ASP.NET     401

View Debug and Trace Information     402

Determine Web Browser Capabilities    404

Redirect to Another Page     405

Use Forms Authentication for User Login     406

Use Master Pages for a Consistent Look     409

Add a Menu     411

Bind Data to a GridView     412

Create a User Control     414

Create a Flexible UI with Web Parts     418

Create a Simple AJAX Page     423

Do Data Validation     425

Maintain Application State     429

Maintain UI State     430

Maintain User Data in a Session     431

Store Session State     433

Use Cookies to Restore Session State     434

Use ASP.NET Model-View-Controller (MVC)     436

Chapter 20  Silverlight     443

Create a Silverlight Project     444

Play a Video     445

Build a Download and Playback Progress Bar     449

Response to Timer Events on the UI Thread      451

Put Content into a 3D Perspective     452

Make Your Application Run out of the Browser      453

Capture a Webcam     455

Print a Document     457


Chapter 21  LINQ     461

Query an Object Collection     462

Order the Results     463

Filter a Collection     464

Get a Collection of a Portion of Objects (Projection)     465

Perform a Join     465

Query XML     466

Create XML     467

Query the Entity Framework     467

Query a Web Service (LINQ to Bing)     469

Speed Up Queries with PLINQ (Parallel LINQ)     472

Chapter 22  Memory Management     473

Measure Memory Usage of Your Application     474

Clean Up Unmanaged Resources Using Finalization     475

Clean Up Managed Resources Using the Dispose Pattern     477

Force a Garbage Collection     482

Create a Cache That Still Allows Garbage Collection     482

Use Pointers     485

Speed Up Array Access     486

Prevent Memory from Being Moved     487

Allocate Unmanaged Memory     488

Chapter 23  Threads, Asynchronous, and Parallel Programming     491

Easily Split Work Among Processors     492

Use Data Structures in Multiple Threads     495

Call a Method Asynchronously     496

Use the Thread Pool     497

Create a Thread     498

Exchange Data with a Thread     499

Protect Data Used in Multiple Threads     500

Use Interlocked Methods Instead of Locks     503

Protect Data in Multiple Processes     504

Limit Applications to a Single Instance     505

Limit the Number of Threads That Can Access a Resource     506

Signal Threads with Events     509

Use a Multithreaded Timer     512

Use a Reader-Writer Lock     513

Use the Asynchronous Programming Model     515

Chapter 24  Reflection and Creating Plugins     519

Enumerate Types in an Assembly     520

Add a Custom Attribute     521

Instantiate a Class Dynamically     523

Invoke a Method on a Dynamically Instantiated Class     523

Implement a Plugin Architecture     525

Chapter 25  Application Patterns and Tips    529

Use a Stopwatch to Profile Your Code     530

Mark Obsolete Code     531

Combine Multiple Events into a Single Event     532

Implement an Observer (aka Subscriber) Pattern     536

Use an Event Broker     540

Remember the Screen Location     543

Implement Undo Using Command Objects     545

Use Model-View-ViewModel in WPF     552

Understand Localization     562

Localize a Windows Forms Application     563

Localize an ASP.NET Application     564

Localize a WPF Application     565

Localize a Silverlight Application     570

Deploy Applications Using ClickOnce     572

Chapter 26  Interacting with the OS and Hardware     575

Get OS, Service Pack, and CLR Version     576

Get CPU and Other Hardware Information     576

Invoke UAC to Request Admin Privileges     578

Write to the Event Log     581

Access the Registry     583

Manage Windows Services     584

Create a Windows Service     585

Call Native Windows Functions Using P/Invoke     588

Call C Functions in a DLL from C#     589

Use Memory-Mapped Files     590

Ensure Your Application Works in Both 32-bit and 64-bit Environments     591

Respond to System Configuration Changes     593

Take Advantage of Windows 7 Features     593

Retrieve Power State Information     595

Chapter 27  Fun Stuff and Loose Ends     597

Create a Nonrectangular Window     598

Create a Notification Icon     602

Create a Screen Saver in WPF     605

Show a Splash Screen     614

Play a Sound File     619

Shuffle Cards     620

Appendix  Essential Tools     621

Reflector     622

NUnit     623

NDepend     626

FXCop     626

Virtual PC     627

Process Explorer and Process Monitor      628

RegexBuddy     630

LINQPad     630

Where to Find More Tools     631

Index     633

More Information

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information

To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.


Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.


If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information

Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.


This site is not directed to children under the age of 13.


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information

If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information

Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents

California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure

Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact

Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice

We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020