Preface

C# is a language targeted at developers for the Microsoft .NET platform. Microsoft portrays C# as a modern and innovative language for .NET development and continues to deliver on that in C# 6.0 with features that help support dynamic programming, parallel programming, and writing less code. C# still allows for both declarative and functional styles of programming, and still includes great object-oriented features as well. In short, C# allows you to use the style of programming that fits your particular problem.

We started writing this book together based on programming problems we ran into when we were first learning C#, and we have continued to expand it based on new challenges and capabilities in the language. In this edition, we have reworked the approach of many solutions to take advantage of the latest innovations in C# like the new expression-level (nameof, string interpolation, null conditional, index initializers), member declaration (auto-property initializers, getter-only auto-properties, expression-bodied function members), and statement-level (exception filters) features. We have also incorporated new uses of dynamic programming (C# 4.0) and asynchronous programming (C# 5.0) into both existing and new recipes to help you understand how to use these language features.

We hope that these additions will help you get past some of the common (and not-so-common) pitfalls and questions everyone has when learning C# for the first time, exploring a new capacity of the language, or working on the slightly off-the-beaten-path items that come up during a development cycle. There are recipes addressing things we found missing from the .NET Framework Class Library (FCL), even though Microsoft has provided tons of functionality to keep folks from reinventing the wheel. Some of these solutions you might immediately use, and some may never darken your door, but we hope this book helps you get the most out of C# and the .NET Framework.

The book is laid out with respect to the types of problems you will solve as you progress through your life as a C# programmer. These solutions are called recipes; each recipe consists of a single problem, its solution, a discussion of the solution and other relevant related information, and finally, a list of resources such as where in the FCL you can find more information about the classes used, other books addressing the topic, related articles, and other recipes. The question/answer format provides complete solutions to problems, making the book easy to read and use. Nearly every recipe contains a complete, documented code sample, showing you how to solve the specific problem, as well as a discussion of how the underlying technology works and a list of alternatives, limitations, and other considerations when appropriate.

Who This Book Is For

You don’t have to be an experienced C# or .NET developer to use this book—it is designed for users of all levels. This book provides solutions to problems that developers face every day as well as some that may come along less frequently. The recipes are targeted at the real-world developer who needs to solve problems now, not learn lots of theory first. While reference or tutorial books can teach general concepts, they do not generally provide the help you need in solving real-world problems. We choose to teach by example, the natural way for most people to learn.

The majority of the problems addressed in this book are frequently faced by C# developers, but some of the more advanced problems call for more intricate solutions that combine many techniques. Each recipe is designed to help you quickly understand the problem, learn how to solve it, and find out any potential trade-offs or ramifications to help you solve your problems quickly, efficiently, and with minimal effort.

To save you even the effort of typing in the solution, we provide the sample code for the book on the O’Reilly website to facilitate the “editor inheritance” mode of development (copy and paste) as well as to help less experienced developers see good programming practice in action. The sample code provides a running test harness that exercises each of the solutions, but the book includes enough of the code in each solution to allow you to implement the solution without the sample code. The sample code is available from the book’s product page (https://github.com/oreillymedia/c_sharp_6_cookbook).

What You Need to Use This Book

To run the samples in this book, you need a computer running Windows 7 or later. A few of the networking and XML solutions require Microsoft Internet Information Server (IIS) version 7.5 or later, and the FTP recipes in Chapter 9 require a locally configured FTP server.

To open and compile the samples in this book, you need Visual Studio 2015. If you are proficient with the downloadable Framework SDK and its command-line compilers, you should not have any trouble following the text of this book and the code samples.

Platform Notes

The solutions in this book were developed using Visual Studio 2015. The differences between C# 6.0 and C# 3.0 are significant, and the sample code has changed from the third edition to reflect that.

It is worth mentioning that although C# is now at version 6.0, the .NET Framework is represented as version 4.6. C# has continued to innovate with each release of the .NET Framework, and now in C# 6.0 there are many capacities in the language to allow you to program in whatever style is best suited to the task at hand.

How This Book Is Organized

This book is organized into 13 chapters, each of which focuses on a particular topic in creating C# solutions. The following paragraphs summarize each chapter to give you an overview of this book’s contents:

Chapter 1, Classes and Generics
This large chapter contains recipes dealing with classes and structure data types as well as the use of generics, which allows you to have code operate uniformly on values of different types. This chapter covers a wide range of recipes, from closures to converting a class to a full-blown command-line argument-processing system to class design topics. There are recipes to enhance your general understanding of generics as well as recipes covering when they are appropriate to use, what support is provided in the Framework for them, and how to create custom implementations of collections.
Chapter 2, Collections, Enumerators, and Iterators
This chapter examines recipes that make use of collections, enumerators, and iterators. The collection recipes make use of—as well as extend the functionality of—the array (single, multi, and jagged), the List<T>, and many other collection classes. The generic-based collections, and the various ways to create your own strongly typed collections, are also discussed. We explore creating custom enumerators, show how you can implement iterators for generic and nongeneric types and use iterators to implement foreach functionality, and cover custom iterator implementations.
Chapter 3, Data Types
This chapter covers strings, numbers, and enumerations. These recipes show how to accomplish things like encode/decode strings, perform numeric conversions, and test strings to determine whether they contain a numeric value. We also cover how to display, convert, and test enumeration types and how to use enumerations that consist of bit flags.
Chapter 4, Language Integrated Query (LINQ) and Lambda Expressions
This chapter covers Language Integrated Query (LINQ) and its usage, including an example of parallel LINQ (PLINQ). There are recipes using many of the standard query operators and showing how to use some of the query operators that are not keywords in the language, but are still quite powerful. Lambda expressions are explored, and recipes show their usage in place of old-style delegates.
Chapter 5, Debugging and Exception Handling
This chapter addresses debugging and exception handling. We present recipes that use data types that fall under the System.Diagnostics namespace, like event logs, processes, performance counters, and custom debugger displays for your types. We also focus on the best ways to implement exception handling in your application. Recipes on preventing unhandled exceptions, reading and displaying stack traces, and throwing/rethrowing exceptions are also included. Finally, we provide recipes showing how to overcome some tricky situations, such as exceptions from late-bound called methods and asynchronous exception handling.
Chapter 6, Reflection and Dynamic Programming
This chapter shows ways to use the built-in assembly inspection system provided by the .NET Framework to determine what types, interfaces, and methods are implemented within an assembly and how to access them in a late-bound fashion. It also shows you how to use dynamic, ExpandoObject, and DynamicObject to accomplish dynamic programming in your applications.
Chapter 7, Regular Expressions
This chapter covers a useful set of classes that are employed to run regular expressions against strings. Recipes enumerate regular expression matches, break up strings into tokens, find/replace characters, and verify the syntax of a regular expression. We also include a recipe that contains many common regular expression patterns.
Chapter 8, Filesystem I/O
This chapter deals with filesystem interactions in three distinct ways: first, it looks at typical file interactions; second, it looks at directory- or folder-based interactions; and third, it deals with advanced filesystem I/O topics.
Chapter 9, Networking and Web
This chapter explores the connectivity options provided by the .NET Framework and how to programmatically access network resources and content on the Web. We include recipes for using TCP/IP directly, using named pipes for communication, building your own port scanner, programmatically determining website configuration, and more.
Chapter 10, XML
If you use .NET, it is likely that you will be dealing with XML to one degree or another. In this chapter, we explore some of the uses for XML and how to program against it using LINQ to XML, the XmlReader/XmlWriter, and XmlDocument. We cover examples using both XPath and XSLT, and topics such as validating XML and transforming XML to HTML.
Chapter 11, Security
There are many ways to write insecure code and only a few ways to write secure code. In this chapter, we explore areas such as controlling access to types, encrypting and decrypting, securely storing data, and using programmatic and declarative security.
Chapter 12, Threading, Synchronization, and Concurrency
This chapter addresses the subject of using multiple threads of execution in a .NET program and issues such as implementing threading in your application, protecting resources from and allowing safe concurrent access, storing per-thread data, running tasks in order, and using the synchronization primitives in .NET to write thread-safe code.
Chapter 13, Toolbox
This chapter has recipes for those random sorts of operations that developers run into over and over again, such as determining locations of system resources, sending email, and working with services. It also covers some less frequently accessed but helpful application pieces, such as queuing messages, running code in a separate AppDomain, and finding the versions of assemblies in the Global Assembly Cache (GAC).

Certain recipes are related; in these cases, the See Also section of the recipe as well as some text in the Discussion will note the relationships.

What Was Left Out

This book is not a reference or a primer about C#. Some good primers and reference books, all from O’Reilly, are C# 6.0 in a Nutshell by Joseph Albahari and Ben Albahari; C# 6.0 Pocket Reference, also by Joseph Albahari and Ben Albahari; and Concurrency in C# Cookbook by Stephen Cleary. The MSDN Library is also invaluable. It is included with Visual Studio 2015 and available online at http://msdn.microsoft.com.

Conventions Used in This Book

This book uses the following typographic conventions:

Italic
Used for URLs, names of directories and files, options, and occasionally for emphasis.
Constant width
Used for program listings and for code items such as commands, options, switches, variables, attributes, keys, functions, types, classes, namespaces, methods, modules, properties, parameters, values, objects, events, event handlers, XML tags, HTML tags, macros, the contents of files, and the output from commands.
Constant width bold
Used in program listings to highlight an important part of the code.
Constant width italic
Used to indicate replaceable parts of code.
//...
Ellipses in C# code indicate text that has been omitted for clarity.
<!--...-->
Ellipses in XML schemas and documents’ code indicate text that has been omitted for clarity.
Note

This icon indicates a tip, suggestion, or general note.

Warning

This icon indicates a warning or caution.

About the Code

Nearly every recipe in this book contains one or more code samples. These samples are included in a single solution and are pieces of code and whole projects that are immediately usable in your application. Most of the code samples are written within a class or structure, making it easier to use within your applications. In addition to this, any using directives are included for each recipe so that you will not have to search for which ones to include in your code.

Complete error handling is included only in critical areas, such as input parameters. This allows you to easily see what is correct input and what is not. Many recipes omit error handling. This makes the solution easier to understand by focusing on the key concepts.

Using Code Examples

The sample code for this book can be found at https://github.com/oreillymedia/c_sharp_6_cookbook.

This book is here to help you get your job done. In general, you may use the code in this book in your programs and documentation. You do not need to contact us for permission unless you’re reproducing a significant portion of the code. For example, writing a program that uses several chunks of code from this book does not require permission. Selling or distributing a CD-ROM of examples from O’Reilly books does require permission. Answering a question by citing this book and quoting example code does not require permission. Incorporating a significant amount of example code from this book into your product’s documentation does require permission.

We appreciate, but do not require, attribution. An attribution usually includes the title, author, publisher, and ISBN. For example: “C# 6.0 Cookbook, Fourth Edition, by Jay Hilyard and Stephen Teilhet. Copyright 2015 Jay Hilyard and Stephen Teilhet, 978-1-4919-2146-3.”

If you feel your use of code examples falls outside fair use or the preceding permission, feel free to contact us at permissions@oreilly.com.

Safari® Books Online

Safari Books Online is an on-demand digital library that delivers expert content in both book and video form from the world’s leading authors in technology and business.

Technology professionals, software developers, web designers, and business and creative professionals use Safari Books Online as their primary resource for research, problem solving, learning, and certification training.

Safari Books Online offers a range of plans and pricing for enterprise, government, education, and individuals.

Members have access to thousands of books, training videos, and prepublication manuscripts in one fully searchable database from publishers like O’Reilly Media, Prentice Hall Professional, Addison-Wesley Professional, Microsoft Press, Sams, Que, Peachpit Press, Focal Press, Cisco Press, John Wiley & Sons, Syngress, Morgan Kaufmann, IBM Redbooks, Packt, Adobe Press, FT Press, Apress, Manning, New Riders, McGraw-Hill, Jones & Bartlett, Course Technology, and hundreds more. For more information about Safari Books Online, please visit us online.

How to Contact Us

Please address comments and questions concerning this book to the publisher:

  • O’Reilly Media, Inc.
  • 1005 Gravenstein Highway North
  • Sebastopol, CA 95472
  • 800-998-9938 (in the United States or Canada)
  • 707-829-0515 (international or local)
  • 707-829-0104 (fax)

We have a web page for this book, where we list errata, examples, and any additional information. You can access this page at http://bit.ly/csharp6_cookbook.

To comment or ask technical questions about this book, send email to .

For more information about our books, courses, conferences, and news, see our website at http://www.oreilly.com.

Find us on Facebook: http://facebook.com/oreilly

Follow us on Twitter: http://twitter.com/oreillymedia

Watch us on YouTube: http://www.youtube.com/oreillymedia

Acknowledgments

This book began for us as we started exploring C# and has continued to evolve over the years as we have used the language in many new and exciting ways. With the introduction of C# 6.0 as well as all of the new features in C# 4.0 and C# 5.0 since the book’s previous edition, we decided it was time to reexamine the first three editions to see how we could improve the existing recipes and learn better ways of accomplishing programming tasks with C#. While we continue to learn an incredible amount about C# and the Framework in general, we’ve worked hard in this edition to bring you a better understanding of how C# has evolved and how it can help you do your job better.

This book would have been impossible without the following people, and we’d like to acknowledge all of their efforts.

Our appreciation goes out to Brian MacDonald (our editor), Heather Scherer, Rachel Monaghan, Nick Adams, and Sara Peyton, who kept us on schedule and did a great job in getting this book finished and on the shelves. Thank you for all of your efforts.

We extend our gratitude and thanks to our technical review team of Steve Munyan, Lee Coward, and Nick Pinkham. We appreciate all the time you all put into helping us make the book better and your insightful commentary. This book would have been impossible to do without your valuable feedback, and we both thank you for it.

From Jay Hilyard

Thanks to Steve Teilhet for his ideas, sense of humor, and willingness to join me yet again on this journey. I always enjoy working with you, even though most of it was on nights and weekends and mostly virtual.

Thanks to my wife, Brooke. Even knowing full well that it would mean time away from our family, you were still supportive, encouraging, and helpful. As always, this was only possible with your help. Thank you, and I love you!

Thanks to my sons, Owen and Drew, who constantly amaze me with your ability to make me look at things from a different angle and who make me proud with all you have accomplished. To have both of you interested in the field I have spent a lifetime in is gratifying, and I couldn’t ask for better sons.

Thanks to Phil and Gail for their support and understanding when I had to work on vacations and for being there to help in ways that only grandparents can, and thanks to my Mom for our monthly dose of sanity.

Thanks to my “flock” of good friends: Seth and Katie Fiermonti, Tom Bebbington, and Jenna Roberts. Friends make everything better, especially when accompanied by good beer. Icon

Thanks to Scott Cronshaw, Bill Bolevic, Melissa Jurkoic, Mike Kennie, Alex Shore, Dave Flanders, Aaron Reddish, Rakshit Jain, Jason Phelps, Josh Clairmont, Bob Blais, Kim Serpa, Stu Savage, Gaurang Patel, Jesse Peters, Ken Jones, Mahesh Unnikrishnan, T Antonio, Mary Ellen Sawyer, Jon Godbout, Atul Kaul, Mark Miller, Rich Labenski, Lance Simpson, Tim Beaulieu, and Lee Horgan for being an awesome team of people to work with. You all work incredibly hard and I appreciate everything you do.

Finally, thanks again to my family and friends for asking about a book they don’t understand and for being excited for me.

From Steve Teilhet

I’m proud to count Jay Hilyard as a good friend, excellent coworker, and hardworking coauthor. It’s not every day that you find a person who is not only a trusted friend, but whom you also work so well with. Thank you for yet another successful book.

Kandis Teilhet, my wife, was there every step of the way to give me the strength to persevere and finish this work. Words cannot express my love for you.

Patrick and Nicholas Teilhet, my two sons, made the rough patches smooth. I couldn’t wish for two better sons. Now that you’re entering your next phase of life, I’m excited to see what both of you will accomplish; perhaps you will write a book as well.

Thanks to my mom, dad, and brother, who are always there to listen and support me.

And last but certainly not least, thanks to the IBM team, Larry Rose, Babita Sharma, Jessica Berliner, Jeff Turnham, John Peyton, Kris Duer, Robert Stanzel, Shu Wang, Bingzhou Zheng, Dave Steinberg, Dave Stewart, Jason Todd, Alexei Pivkine, Joshua Clark, William Frontiero, Matthew Murphy, Omer Trip, Marco Pistoia, Enrique Varillas, Guillermo Hurtado, Bao Lu, Mary Santo, Diane Redfearn, Urmi Chatterjee, Joshua Ho, Kenneth Cheung, Andrew Mak, Daniel Nguyen, Jennifer Calder, Tahseen Shabab, Srinivas Sripada, David Marshak, Larry Gerard, Douglas Wilson, Steve Hikida, and so many others. Your hard work and brilliance are inspiring.

Get C# 6.0 Cookbook, 4th Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.