ptg18189312 D E I T E L® D E V E L O P E R S E R I E S COMMENTS FROM RECENT EDITIONS REVIEWERS (Continued From Back Cover) “I really love the way you guys write—it’s interesting and informative!”—Shay Friedman, Microsoft Visual C# MVP The DEITEL® DEVELOPER SERIES is designed for professional programmers. The series presents “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 focused treatments on a growing list of emerging and mature technologies, including C# and .NET, 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 C++, C, JavaScript®, Internet and web development, Android™ app development, Java™, iOS® app online.” —Shawn Weisfeld, Microsoft MVP and President and Founder of UserGroup.tv development, Swift™ and more. Each book in the series contains the same live-code teaching “Outstanding presentations of Windows Forms and the .NET I/O facilities. Amazingly clear and intuitive presentation of generics; this chapter represents methodology used in the Deitels’ HOW TO PROGRAM SERIES college textbooks—in this book, 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 most concepts are presented in the context of completely coded, live apps. 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 ABOUT THE COVER how many ways one can improve it until it pretty much becomes air-tight in security and functionality. Operator overloading is a good description. The cover of this book features a fractal—a geometric figure that can be generated from a pattern Good example of extension methods.” —Bradley Sward, College of Dupage repeated recursively. The figure is modified by applying the pattern to each segment of the original “Updating an already excellent book with the latest .NET features can only result in a superb product. I like the explanation of properties and figure. Although these figures were studied before the 20th century, it was the mathematician 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 Benoit Mandelbrot who in the 1970s introduced the term fractal, along with the specifics of how favorites. Great job explaining inheritance, polymorphism, interfaces and operator overloading.” a fractal is created and practical applications. Fractal geometry provides mathematical models for —José Antonio González Seco, Parliament of Andalusia, Spain many complex forms found in nature, such as mountains, clouds, galaxy clusters and the folds of “Great job explaining exception handling—with great examples; the new features look pretty sweet. Shows the important things you need the brain. Not all fractals resemble objects in nature. Drawing fractals has become a popular art form. 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 ptg18189312 “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 Cover illustration by Lisa Ewing/GettyImages “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 DEITEL & ASSOCIATES, INC. 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. Deitel & Associates, Inc., founded by Paul Deitel and Harvey Deitel, is an internationally recognized The card shuffling and dealing simulation is a great example for bringing together many concepts. Good use of overloaded functions for authoring and corporate training organization, specializing in computer programming languages, rectangular arrays and jagged arrays. The LINQ chapter is perfect—much more will be revealed in later chapters but readers will remember object technology, Internet and web software technology, and Android and iOS app development. The 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. company’s clients include many of the world’s largest corporations, government agencies, branches of Describes inheritance perfectly.” —Bradley Sward, College of Dupage the military and academic institutions. The company offers instructor-led training courses delivered at “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 client sites worldwide on major programming languages and platforms. Through its 40-year publishing 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 partnership with Prentice Hall/Pearson, Deitel & Associates, Inc., creates leading-edge programming topic as asynchronous programming.”—José Antonio González Seco, Parliament of Andalusia, Spain professional books, college textbooks, LiveLessons™ video products, e-books and REVEL™ interactive “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 multimedia courses (revel.pearson.com) with integrated labs and assessment. To learn more about 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 Deitel & Associates, Inc., its text and video publications and its worldwide instructor-led, on-site training formats and using them well.”—Lucian Wischik, C# Language Design Team, Microsoft curriculum, visit www.deitel.com/or send an email to [email protected]. Join the Deitel social “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 media communities on Facebook® (facebook.com/DeitelFan), Twitter® (twitter.com/deitel), 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 Google+™ (google.com/+DeitelFan), LinkedIn® (bit.ly/DeitelLinkedIn) and YouTube™ 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 nicetouch. (youtube.com/DeitelTV), and subscribe to the Deitel® Buzz Online newsletter (www.deitel.com/ Good example of serialization. The recursive directory searching is nice.”—Bradley Sward, College of Dupage newsletter/subscribe.html). 7/7/16 12:31 PM C# 6 P FOR ROGRAMMERS S E IXTH DITION D ® D S EITEL EVELOPER ERIES ptg18189312 Many of the designations used by manufacturers and sellers to distinguish their products are claimed as trademarks. Where those designations appear in this book, and the publisher was aware of a trademark claim, the designations have been printed with initial capital letters or in all capitals. The authors and publisher have taken care in the preparation of this book, but make no expressed or implied warranty of any kind and assume no responsibility for errors or omissions. No liability is assumed for incidental or consequential damages in connection with or arising out of the use of the information or programs contained herein. Microsoft and/or its respective suppliers make no representations about the suitability of the information contained in the documents and related graphics published as part of the services for any purpose. All such documents and related graphics are provided “as is” without warranty of any kind. Microsoft and/or its respective suppliers hereby disclaim all warranties and conditions with regard to this information, including all warranties and conditions of merchantabi- lity, whether express, implied or statutory, fitness for a particular purpose, title and non-infringement. In no event shall Microsoft and/or its respective suppliers be liable for any special, indirect or consequential damages or any damages whatsoever resulting from loss of use, data or profits, whether in an action of contract, negligence or other tortious action, arising out of or in connection with the use or performance of information available from the services. The documents and related graphics contained herein could include technical inaccuracies or typographical errors. Changes are periodically added to the information herein. Microsoft and/or its respective suppliers may make improve- ments and/or changes in the product(s) and/or the program(s) described herein at any time. Partial screen shots may be viewed in full within the software version specified. The publisher offers excellent discounts on this book when ordered in quantity for bulk purchases or special sales, which may include electronic versions and/or custom covers and content particular to your business, training goals, marketing focus, and branding interests. ptg18189312 For government sales inquiries, please contact [email protected]. For questions about sales outside the U.S., please contact [email protected]. Visit us on the Web: informit.com/ph Library of Congress Control Number: 2016946157 Copyright © 2017 Pearson Education, Inc. All rights reserved. Printed in the United States of America. This publication is protected by copyright, and permission must be obtained from the publisher prior to any prohibited reproduction, storage in a retrieval system, or transmission in any form or by any means, electronic, mechanical, photocopying, recording, or likewise. For information regarding permissions, request forms and the appropriate contacts within the Pearson Education Global Rights & Permissions Department, please visit www.pearsoned.com/permissions/. ISBN-13: 978-0-13-459632-7 ISBN-10: 0-13-459632-3 Text printed in the United States at RR Donnelley in Crawfordsville, Indiana. First printing, August 2016 C# 6 P FOR ROGRAMMERS S E IXTH DITION D ® D S EITEL EVELOPER ERIES Paul Deitel Deitel & Associates, Inc. ptg18189312 Harvey Deitel Deitel & Associates, Inc. Boston (cid:129) Columbus (cid:129) Indianapolis (cid:129) New York (cid:129) San Francisco (cid:129) Amsterdam (cid:129) Cape Town Dubai (cid:129) London (cid:129) Madrid (cid:129) Milan (cid:129) Munich (cid:129) Paris (cid:129) Montreal (cid:129) Toronto (cid:129) Delhi (cid:129) Mexico City São Paulo (cid:129) Sydney (cid:129) Hong Kong (cid:129) Seoul (cid:129) Singapore (cid:129) Taipei (cid:129) Tokyo D e i t e l ® S e r i e s P a g e Deitel® Developer Series VitalSource Web Books Android™ 6 for Programmers: An App-Driven http://bit.ly/DeitelOnVitalSource Approach, 3/E Android™ How to Program, 2/E and 3/E C for Programmers with an Introduction to C11 C++ How to Program, 8/E and 9/E C++11 for Programmers Java™ How to Program, 9/E and 10/E C# 6 for Programmers Simply C++: An App-Driven Tutorial Approach iOS® 8 for Programmers: An App-Driven Simply Visual Basic® 2010: An App-Driven Approach with Swift™ Approach, 4/E Java™ for Programmers, 3/E Visual Basic® 2012 How to Program, 6/E JavaScript for Programmers Visual C#® 2012 How to Program, 5/E Swift™ for Programmers Visual C#® How to Program, 6/E How To Program Series LiveLessons Video Learning Products Android™ How to Program, 3/E http://informit.com/deitel C++ How to Program, 10/E Android™ 6 App Development Fundamentals, 3/E C How to Program, 8/E C++ Fundamentals Java™ How to Program, Early Objects Version, 10/E Java™ Fundamentals, 2/E Java™ How to Program, Late Objects Version, 10/E C# 6 Fundamentals Internet & World Wide Web How to Program, 5/E C# 2012 Fundamentals Visual Basic® 2012 How to Program, 6/E iOS® 8 App Development Fundamentals with ptg18189312 Visual C#® How to Program, 6/E Swift™, 3/E Simply Series JavaScript Fundamentals Swift™ Fundamentals Simply Visual Basic® 2010: An App-Driven REVEL™ Interactive Multimedia Approach, 4/E Simply C++: An App-Driven Tutorial Approach REVEL™ for Deitel Java™ To receive updates on Deitel publications, Resource Centers, training courses, partner offers and more, please join the Deitel communities on (cid:129) Facebook®—http://facebook.com/DeitelFan (cid:129) Twitter®—http://twitter.com/deitel (cid:129) LinkedIn®—http://linkedin.com/company/deitel-&-associates (cid:129) YouTube™—http://youtube.com/DeitelTV (cid:129) Google+™—http://google.com/+DeitelFan and register for the free Deitel® Buzz Online e-mail newsletter at: http://www.deitel.com/newsletter/subscribe.html To communicate with the authors, send e-mail to: [email protected] For information on programming-languages corporate training seminars offered by Deitel & Associates, Inc. worldwide, write to [email protected] or visit: http://www.deitel.com/training/ For continuing updates on Pearson/Deitel publications visit: http://www.deitel.com http://www.pearsonhighered.com/deitel/ Visit the Deitel Resource Centers, which will help you master programming languages, software develop- ment, Android™ and iOS® app development, and Internet- and web-related topics: http://www.deitel.com/ResourceCenters.html Trademarks DEITEL and the double-thumbs-up bug are registered trademarks of Deitel and Associates, Inc. Microsoft® and Windows® are registered trademarks of the Microsoft Corporation in the U.S.A. and other countries. This book is not sponsored or endorsed by or affiliated with the Microsoft Corporation. UNIX is a registered trademark of The Open Group. Throughout this book, trademarks are used. Rather than put a trademark symbol in every occurrence of a trademarked name, we state that we are using the names in an editorial fashion only and to the benefit of the trademark owner, with no intention of infringement of the trademark. ptg18189312 In memory of William Siebert, Professor Emeritus of Electrical Engineering and Computer Science at MIT: Your use of visualization techniques in your Signals and Systems lectures inspired the way generations of engineers, computer scientists, educators and authors present their work. Harvey and Paul Deitel ptg18189312 Contents Preface xxi Before You Begin xxxii 1 Introduction 1 1.1 Introduction 2 1.2 Object Technology: A Brief Review 2 1.3 C# 5 1.3.1 Object-Oriented Programming 5 ptg18189312 1.3.2 Event-Driven Programming 6 1.3.3 Visual Programming 6 1.3.4 Generic and Functional Programming 6 1.3.5 An International Standard 6 1.3.6 C# on Non-Windows Platforms 6 1.3.7 Internet and Web Programming 7 1.3.8 Asynchronous Programming with async and await 7 1.4 Microsoft’s .NET 7 1.4.1 .NET Framework 7 1.4.2 Common Language Runtime 7 1.4.3 Platform Independence 8 1.4.4 Language Interoperability 8 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 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.2.1 Introduction to Visual Studio Community 2015 16 2.2.2 Visual Studio Themes 17 2.2.3 Links on the Start Page 17 2.2.4 Creating a New Project 18 2.2.5 New Project Dialog and Project Templates 19 2.2.6 Forms and Controls 20 viii Contents 2.3 Menu Bar and Toolbar 21 2.4 Navigating the Visual Studio IDE 24 2.4.1 Solution Explorer 25 2.4.2 Toolbox 26 2.4.3 Properties Window 26 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 3 Introduction to C# App Programming 40 3.1 Introduction 41 3.2 Simple App: Displaying a Line of Text 41 3.2.1 Comments 42 3.2.2 using Directive 43 3.2.3 Blank Lines and Whitespace 43 3.2.4 Class Declaration 43 3.2.5 Main Method 46 ptg18189312 3.2.6 Displaying a Line of Text 46 3.2.7 Matching Left ({) and Right (}) Braces 47 3.3 Creating a Simple App in Visual Studio 47 3.3.1 Creating the Console App 47 3.3.2 Changing the Name of the App File 48 3.3.3 Writing Code and Using IntelliSense 49 3.3.4 Compiling and Running the App 51 3.3.5 Errors, Error Messages and the Error List Window 51 3.4 Modifying Your Simple C# App 52 3.4.1 Displaying a Single Line of Text with Multiple Statements 52 3.4.2 Displaying Multiple Lines of Text with a Single Statement 53 3.5 String Interpolation 55 3.6 Another C# App: Adding Integers 56 3.6.1 Declaring the int Variable number1 57 3.6.2 Declaring Variables number2 and sum 57 3.6.3 Prompting the User for Input 58 3.6.4 Reading a Value into Variable number1 58 3.6.5 Prompting the User for Input and Reading a Value into number2 59 3.6.6 Summing number1 and number2 59 3.6.7 Displaying the sum with string Interpolation 59 3.6.8 Performing Calculations in Output Statements 59 3.7 Arithmetic 59 3.7.1 Arithmetic Expressions in Straight-Line Form 60 3.7.2 Parentheses for Grouping Subexpressions 60 3.7.3 Rules of Operator Precedence 60 3.8 Decision Making: Equality and Relational Operators 61 3.9 Wrap-Up 65