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.
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).
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.
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.
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:
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.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.dynamic
, ExpandoObject
, and DynamicObject
to accomplish dynamic programming in your applications.XmlReader
/XmlWriter
, and XmlDocument
. We cover examples using both XPath and XSLT, and topics such as validating XML and transforming XML to HTML.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.
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.
This book uses the following typographic conventions:
Constant width
Constant width bold
Constant width italic
//...
<!--...-->
This icon indicates a tip, suggestion, or general note.
This icon indicates a warning or caution.
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.
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 [email protected].
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.
Please address comments and questions concerning this book to the publisher:
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 [email protected].
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
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.
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.
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.
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.