C# 6 For Programmers by Paul J. DeitelC# 6 For Programmers by Paul J. Deitel

C# 6 For Programmers

byPaul J. Deitel, Harvey Deitel

Paperback | August 2, 2016

Pricing and Purchase Info


Earn 345 plum® points

Ships within 1-2 weeks

Ships free on orders over $25

Not available in stores


The professional programmer’s Deitel® guide to C# 6 and object-oriented development for Windows®


Written for programmers with a background in high-level language programming, C# 6 for Programmers applies the Deitel signature live-code approach to teaching programming and explores Microsoft’s C# 6 and .NET in depth. Concepts are presented in the context of 170+ fully coded and tested apps, complete with syntax shading, code highlighting, code walkthroughs, program outputs and hundreds of savvy software-development tips.

Start with an introduction to C# using an early classes and objects approach, then rapidly move on to more advanced topics, including LINQ, asynchronous programming with async and await and more. You’ll enjoy the treatment of object-oriented programming and an object-oriented design/UML® ATM case study, including a complete C# implementation. When you’ve mastered the book, you’ll be ready to start building industrial-strength, object-oriented C# apps.

Paul Deitel and Harvey Deitel are the founders of Deitel & Associates, Inc., the internationally recognized programming languages authoring and corporate training organization. Millions of people worldwide have used Deitel textbooks, professional books, LiveLessons™ video products, e-books, resource centers and REVEL™ interactive multimedia courses with integrated labs and assessment to master major programming languages and platforms, including C#, C++, C, Java™, Android™ app development, iOS app development, Swift™, Visual Basic®, Python™ and Internet and web programming.



  • Use with Windows® 7, 8 or 10.
  • Integrated coverage of new C# 6 functionality: string interpolation, expression-bodied methods and properties, auto-implemented property initializers, getter-only properties, nameof, null-conditional operator, exception filters and more.
  • Entertaining and challenging code examples.
  • Deep treatment of classes, objects, inheritance, polymorphism and interfaces.
  • Generics, LINQ and generic collections; PLINQ (Parallel LINQ) for multicore performance.
  • Asynchronous programming with async and await; functional programming with lambdas, delegates and immutability.
  • Files; relational database with LINQ to Entities.
  • Object-oriented design ATM case study with full code implementation.
  • Emphasis on performance and software engineering principles.


Visit www.deitel.com

  • Download code examples
  • For Deitel’s programming training courses, www.deitel.com/training or write to deitel@deitel.com
  • Join the Deitel social networking communities:
    • Facebook® at facebook.com/DeitelFan
    • Twitter® at twitter.com/deitel
    • LinkedIn® at bit.ly/DeitelLinkedIn
    • YouTube™ at youtube.com/DeitelTV
    • Google+™ at google.com/+DeitelFan
  • Subscribe to the Deitel® Buzz e-mail newsletter at www.deitel.com/newsletter/subscribe.html
Title:C# 6 For ProgrammersFormat:PaperbackDimensions:768 pages, 9 × 7 × 1.1 inPublished:August 2, 2016Publisher:Pearson EducationLanguage:English

The following ISBNs are associated with this title:

ISBN - 10:0134596323

ISBN - 13:9780134596327


Table of Contents

Preface xxi

Before You Begin xxxii


Chapter 1: Introduction 1

1.1 Introduction 2

1.2 Object Technology: A Brief Review 2

1.3 C# 5

1.4 Microsoft’s .NET 7

1.5 Microsoft’s Windows® Operating System 8

1.6 Visual Studio Integrated Development Environment 10

1.7 Painter Test-Drive in Visual Studio Community 10


Chapter 2: Introduction to Visual Studio and Visual Programming 15

2.1 Introduction 16

2.2 Overview of the Visual Studio Community 2015 IDE 16

2.3 Menu Bar and Toolbar 21

2.4 Navigating the Visual Studio IDE 24

2.5 Help Menu and Context-Sensitive Help 28

2.6 Visual Programming: Creating a Simple App that Displays Text and an Image 29

2.7 Wrap-Up 38

2.8 Web Resources 39


Chapter 3: Introduction to C# App Programming 40

3.1 Introduction 41

3.2 Simple App: Displaying a Line of Text 41

3.3 Creating a Simple App in Visual Studio 47

3.4 Modifying Your Simple C# App 52

3.5 String Interpolation 55

3.6 Another C# App: Adding Integers 56

3.7 Arithmetic 59

3.8 Decision Making: Equality and Relational Operators 61

3.9 Wrap-Up 65


Chapter 4: Introduction to Classes, Objects, Methods and strings 67

4.1 Introduction 68

4.2 Test-Driving an Account Class 69

4.3 Account Class with an Instance Variable and Set and Get Methods 71

4.4 Creating, Compiling and Running a Visual C# Project with Two Classes 77

4.5 Software Engineering with Set and Get Methods 78

4.6 Account Class with a Property Rather Than Set and Get Methods 79

4.7 Auto-Implemented Properties 83

4.8 Account Class: Initializing Objects with Constructors 84

4.9 Account Class with a Balance; Processing Monetary Amounts 87

4.10 Wrap-Up 93


Chapter 5: Control Statements: Part 1 95

5.1 Introduction 96

5.2 Control Structures 96

5.3 if Single-Selection Statement 99

5.4 if…else Double-Selection Statement 100

5.5 Student Class: Nested if…else Statements 103

5.6 while Iteration Statement 106

5.7 Counter-Controlled Iteration 107

5.8 Sentinel-Controlled Iteration 110

5.9 Nested Control Statements 114

5.10 Compound Assignment Operators 117

5.11 Increment and Decrement Operators 118

5.12 Simple Types 121

5.13 Wrap-Up 121


Chapter 6: Control Statements: Part 2 123

6.1 Introduction 124

6.2 Essentials of Counter-Controlled Iteration 124

6.3 for Iteration Statement 125

6.4 App: Summing Even Integers 128

6.5 App: Compound-Interest Calculations 129

6.6 do…while Iteration Statement 132

6.7 switch Multiple-Selection Statement 133

6.8 Class AutoPolicy Case Study: strings in switch Statements 139

6.9 break and continue Statements 141

6.10 Logical Operators 143

6.11 Wrap-Up 149


Chapter 7: Methods: A Deeper Look 150

7.1 Introduction 151

7.2 Packaging Code in C# 152

7.3 static Methods, static Variables and Class Math 152

7.4 Methods with Multiple Parameters 155

7.5 Notes on Using Methods 159

7.6 Argument Promotion and Casting 160

7.7 The .NET Framework Class Library 162

7.8 Case Study: Random-Number Generation 164

7.9 Case Study: A Game of Chance; Introducing Enumerations 169

7.10 Scope of Declarations 174

7.11 Method-Call Stack and Activation Records 177

7.12 Method Overloading 181

7.13 Optional Parameters 183

7.14 Named Parameters 184

7.15 C# 6 Expression-Bodied Methods and Properties 185

7.16 Recursion 186

7.17 Value Types vs. Reference Types 189

7.18 Passing Arguments By Value and By Reference 190

7.19 Wrap-Up 194


Chapter 8: Arrays; Introduction to Exception Handling 195

8.1 Introduction 196

8.2 Arrays 197

8.3 Declaring and Creating Arrays 198

8.4 Examples Using Arrays 199

8.5 Using Arrays to Analyze Survey Results; Intro to Exception Handling 208

8.6 Case Study: Card Shuffling and Dealing Simulation 212

8.7 Passing Arrays and Array Elements to Methods 216

8.8 Case Study: GradeBook Using an Array to Store Grades 219

8.9 Multidimensional Arrays 225

8.10 Case Study: GradeBook Using a Rectangular Array 230

8.11 Variable-Length Argument Lists 236

8.12 Using Command-Line Arguments 237

8.13 (Optional) Passing Arrays by Value and by Reference 240

8.14 Wrap-Up 244


Chapter 9: Introduction to LINQ and the List Collection 245

9.1 Introduction 246

9.2 Querying an Array of int Values Using LINQ 247

9.3 Querying an Array of Employee Objects Using LINQ 251

9.4 Introduction to Collections 256

9.5 Querying the Generic List Collection Using LINQ 261

9.6 Wrap-Up 264

9.7 Deitel LINQ Resource Center 264


Chapter 10: Classes and Objects: A Deeper Look 265

10.1 Introduction 266

10.2 Time Class Case Study; Throwing Exceptions 266

10.3 Controlling Access to Members 270

10.4 Referring to the Current Object’s Members with the this Reference 271

10.5 Time Class Case Study: Overloaded Constructors 273

10.6 Default and Parameterless Constructors 279

10.7 Composition 280

10.8 Garbage Collection and Destructors 284

10.9 static Class Members 284

10.10 readonly Instance Variables 288

10.11 Class View and Object Browser 289

10.12 Object Initializers 291

10.13 Operator Overloading; Introducing struct 291

10.14 Time Class Case Study: Extension Methods 295

10.15 Wrap-Up 298


Chapter 11: Object-Oriented Programming: Inheritance 299

11.1 Introduction 300

11.2 Base Classes and Derived Classes 301

11.3 protected Members 303

11.4 Relationship between Base Classes and Derived Classes 304

11.5 Constructors in Derived Classes 324

11.6 Software Engineering with Inheritance 324

11.7 Class object 325

11.8 Wrap-Up 326


Chapter 12: OOP: Polymorphism and Interfaces 327

12.1 Introduction 328

12.2 Polymorphism Examples 330

12.3 Demonstrating Polymorphic Behavior 331

12.4 Abstract Classes and Methods 334

12.5 Case Study: Payroll System Using Polymorphism 336

12.6 sealed Methods and Classes 351

12.7 Case Study: Creating and Using Interfaces 352

12.8 Wrap-Up 361


Chapter 13: Exception Handling: A Deeper Look 362

13.1 Introduction 363

13.2 Example: Divide by Zero without Exception Handling 364

13.3 Example: Handling DivideByZeroExceptions and FormatExceptions 367

13.4 .NET Exception Hierarchy 372

13.5 finally Block 374

13.6 The using Statement 381

13.7 Exception Properties 382

13.8 User-Defined Exception Classes 386

13.9 Checking for null References; Introducing C# 6’s ?. Operator 390

13.10 Exception Filters and the C# 6 when Clause 392

13.11 Wrap-Up 393


Chapter 14: Graphical User Interfaces with Windows Forms: Part 1 394

14.1 Introduction 395

14.2 Windows Forms 396

14.3 Event Handling 398

14.4 Control Properties and Layout 406

14.5 Labels, TextBoxes and Buttons 410

14.6 GroupBoxes and Panels 413

14.7 CheckBoxes and RadioButtons 416

14.8 PictureBoxes 424

14.9 ToolTips 426

14.10 NumericUpDown Control 428

14.11 Mouse-Event Handling 430

14.12 Keyboard-Event Handling 433

14.13 Wrap-Up 436


Chapter 15: Graphical User Interfaces with Windows Forms: Part 2 438

15.1 Introduction 439

15.2 Menus 439

15.3 MonthCalendar Control 449

15.4 DateTimePicker Control 450

15.5 LinkLabel Control 453

15.6 ListBox Control 456

15.7 CheckedListBox Control 461

15.8 ComboBox Control 464

15.9 TreeView Control 468

15.10 ListView Control 474

15.11 TabControl Control 480

15.12 Multiple Document Interface (MDI) Windows 484

15.13 Visual Inheritance 492

15.14 User-Defined Controls 497

15.15 Wrap-Up 500


Chapter 16: Strings and Characters: A Deeper Look 502

16.1 Introduction 503

16.2 Fundamentals of Characters and Strings 504

16.3 string Constructors 505

16.4 string Indexer, Length Property and CopyTo Method 506

16.5 Comparing strings 507

16.6 Locating Characters and Substrings in strings 511

16.7 Extracting Substrings from strings 514

16.8 Concatenating strings 515

16.9 Miscellaneous string Methods 515

16.10 Class StringBuilder 517

16.11 Length and Capacity Properties, EnsureCapacity Method and Indexer of Class StringBuilder 518

16.12 Append and AppendFormat Methods of Class StringBuilder 520

16.13 Insert, Remove and Replace Methods of Class StringBuilder 522

16.14 Char Methods 525

16.15 Introduction to Regular Expressions (Online) 527

16.16 Wrap-Up 527


Chapter 17: Files and Streams 529

17.1 Introduction 530

17.2 Files and Streams 530

17.3 Creating a Sequential-Access Text File 531

17.4 Reading Data from a Sequential-Access Text File 540

17.5 Case Study: Credit-Inquiry Program 544

17.6 Serialization 549

17.7 Creating a Sequential-Access File Using Object Serialization 550

17.8 Reading and Deserializing Data from a Binary File 554

17.9 Classes File and Directory 557

17.10 Wrap-Up 565


Chapter 18: Generics 567

18.1 Introduction 568

18.2 Motivation for Generic Methods 569

18.3 Generic-Method Implementation 571

18.4 Type Constraints 574

18.5 Overloading Generic Methods 577

18.6 Generic Classes 577

18.7 Wrap-Up 587


Chapter 19: Generic Collections; Functional Programming with LINQ/PLINQ 588

19.1 Introduction 589

19.2 Collections Overview 590

19.3 Class Array and Enumerators 593

19.4 Dictionary Collections 597

19.5 Generic LinkedList Collection 603

19.6 C# 6 Null Conditional Operator ?[] 607

19.7 C# 6 Dictionary Initializers and Collection Initializers 608

19.8 Delegates 608

19.9 Lambda Expressions 611

19.10 Introduction to Functional Programming 614

19.11 Functional Programming with LINQ Method-Call Syntax and Lambdas 616

19.11.1 LINQ Extension Methods Min, Max, Sum and Average 619

19.11.2 Aggregate Extension Method for Reduction Operations 619

19.11.3 The Where Extension Method for Filtering Operations 621

19.11.4 Select Extension Method for Mapping Operations 622

19.12 PLINQ: Improving LINQ to Objects Performance with Multicore 622

19.13 (Optional) Covariance and Contravariance for Generic Types 626

19.14 Wrap-Up 628


Chapter 20: Databases and LINQ 629

20.1 Introduction 630

20.2 Relational Databases 631

20.3 A Books Database 632

20.4 LINQ to Entities and the ADO.NET Entity Framework 636

20.5 Querying a Database with LINQ 637

20.6 Dynamically Binding Query Results 651

20.7 Retrieving Data from Multiple Tables with LINQ 655

20.8 Creating a Master/Detail View App 661

20.9 Address Book Case Study 664

20.10 Tools and Web Resources 671

20.11 Wrap-Up 671


Chapter 21: Asynchronous Programming with async and await 672

21.1 Introduction 673

21.2 Basics of async and await 675

21.3 Executing an Asynchronous Task from a GUI App 676

21.4 Sequential Execution of Two Compute-Intensive Tasks 680

21.5 Asynchronous Execution of Two Compute-Intensive Tasks 682

21.6 Invoking a Flickr Web Service Asynchronously with HttpClient 687

21.7 Displaying an Asynchronous Task’s Progress 694

21.8 Wrap-Up 698


Appendix A: Operator Precedence Chart 700


Appendix B: Simple Types 702


Appendix C: ASCII Character Set 704


Index 705

Editorial Reviews

Comments from Recent Editions’ Reviewers   “Takes you from zero to the highest levels of C# programming proficiency, preparing you to tackle the most frequent requirements in modern software development. The code examples really shine. The best presentation of inheritance, interfaces and polymorphism I’ve seen in my 30+ years as a trainer and consultant. I like the early introduction to LINQ and .NET collections, and the coverage of LINQ to Entities for relational databases. Shows the techniques needed to develop real-world apps, including key topics, such as async and await.” —Octavio Hernandez, Microsoft Certified Solution Developer (MCSD), Principal Software Engineer at Advanced Bionics   “This book’s treatment of LINQ and PLINQ is excellent—I liked how it led naturally to functional programming idioms—skills that will serve professionals best for their future. Also, it was great to see performance testing on multicore systems.” —Lucian Wischik, C# Language Design Team, Microsoft   “The ultimate book on programming with Microsoft technologies.” —Kirill Osenkov, Visual Studio Languages Team, Microsoft   “Excellent introduction to the world of .NET for the beginning C# programmer, using the Deitels’ live-code approach and real-world examples.” —Bonnie Berent, Microsoft C# MVP   “Illustrates the best practices of C# programming. Teaches how to ‘program in the large,’ with material on object-oriented programming and software engineering principles.” —Mingsheng Hong, Cornell University   “I like the chapter on asynchronous programming with async and await—this is the future of programming, and making these types of tasks ‘easy’ to program is going to be key to any programming language. The introduction to multi-threading was interesting. It was good to see synchronous versus asynchronous programming head-to-head. The flickr web services demo was awesome.” —Bradley Sward, College of Dupage   “I really love the way you guys write—it’s interesting and informative!” —Shay Friedman, Microsoft Visual C# MVP   “Good introduction to the most popular GUI controls and working with events. I use the techniques of the strings chapter in the line of business apps that I build. I liked the files and streams chapter and the real-world example. I’m pleased to see the inclusion of additional advanced material online.” —Shawn Weisfeld, Microsoft MVP and President and Founder of UserGroup.tv   “Outstanding presentations of Windows Forms and the .NET I/O facilities. Amazingly clear and intuitive presentation of generics; this chapter represents why I like this book so much—it really shines at presenting advanced topics in a way that can be easily understood. The presentation of LINQ to XML is fabulous.” —Octavio Hernandez, Microsoft Certified Solution Developer (MCSD), Principal Software Engineer at Advanced Bionics   “The beginning of the chapter ‘Classes and Objects: A Deeper Look’ shows a class in an ‘amateur’ state—then you do a great job of describing how many ways one can improve it until it pretty much becomes air-tight in security and functionality. Operator overloading is a good description. Good example of extension methods.” —Bradley Sward, College of Dupage   “Updating an already excellent book with the latest .NET features can only result in a superb product. I like the explanation of properties and the discussion of value vs. reference types. I like your explanation of pass-by-value vs. pass-by-reference. The arrays chapter is one of my favorites. Great job explaining inheritance, polymorphism, interfaces and operator overloading.” —José Antonio González Seco, Parliament of Andalusia, Spain   “Great job explaining exception handling—with great examples; the new features look pretty sweet. Shows the important things you need to get going with GUI. Delegates are huge and covered well. Interesting description of C# 6’s exception filters.” —Bradley Sward, College of Dupage   “An excellent introduction to XML, LINQ to XML and related technologies.” —Helena Kotas, Microsoft   “Good overview of relational databases—it hits on the right LINQ idioms.” —Alex Turner, Microsoft   “Excellent chapter on exceptions.” —Vinay Ahuja, Architect, Microsoft Corporation   “Great chapter on polymorphism.” —Eric Lippert, Formerly of Microsoft   “Introduction to LINQ and the List Collection is a great chapter; you do such a good and consistent job of explaining your code. The focus on using LINQ to manage data is cutting edge.” —Stephen Hustedde, South Mountain College   “The presentations are always superbly clear. Excellent intro to Visual Studio and visual programming! I like the early presentation of the new C# 6 string interpolation feature. Introducing UML class diagrams in parallel with the presentation of the language is a great idea. I like the early introduction of exception handling. Brings readers up to speed fast in GUI design and implementation, and event-driven programming. Nice example demonstrating the method call stack and activation records. Database chapter perfectly explains LINQ to Entities and UI binding.” —Octavio Hernandez, Microsoft Certified Solution Developer (MCSD), Principal Software Engineer at Advanced Bionics   “Chapter 2 is perfect for introducing Visual Studio and GUI elements—I wish I had this chapter when I was first getting back into computers. Everything felt just right in the methods chapter. Recursion will warp anyone’s brain—the stack discussion really helps readers understand what is going on. I really like the deck of cards example, being a former casino gaming programmer. Multidimensional arrays are handled well. I like the attention to detail and the UML. Thank you for showing correct code-formatting conventions. Thorough display of all the ‘pass-by’ types. The card shuffling and dealing simulation is a great example for bringing together many concepts. Good use of overloaded functions for rectangular arrays and jagged arrays. The LINQ chapter is perfect—much more will be revealed in later chapters but readers will remember this. The collections are a nice addition as well—a chapter that is important to get a taste of now so the later material can be feasted upon. Describes inheritance perfectly.” —Bradley Sward, College of Dupage   “This new edition solidifies it as the fundamental tool for learning C# updated to the latest C# 6 features. It covers from the fundamentals of OOP to the most advanced topics, all in an easily accessible way thanks to its crystal-clear explanations. A good job explaining such a complex topic as asynchronous programming.” —José Antonio González Seco, Parliament of Andalusia, Spain   “I liked the natural use of C# 6 string interpolation. A good clear explanation of LINQ query syntax. GUI apps are where coding starts to become fun—you’ve handled it well and covered all the bases. The Game of Craps is an awesome example. I love that you’re paying attention to formats and using them well.” —Lucian Wischik, C# Language Design Team, Microsoft   “An excellent resource to tame the beast that is C#. In the Windows forms chapter, cool how the message box will be customized to the clicked buttons. I love the Paint example. A good look at files and directories—with text mode it’s easier to see what’s going on—binary mode is much more efficient so it’s good to see it here. You show error checking in GUI and files/streams well. File chooser functionality is a nice touch. Good example of serialization. The recursive directory searching is nice.” —Bradley Sward, College of Dupage