Illustrated C# 7 The C# Language Presented Clearly, Concisely, and Visually — Fifth Edition — Daniel Solis Cal Schrotenboer Illustrated C# 7 The C# Language Presented Clearly, Concisely, and Visually Fifth Edition Daniel Solis Cal Schrotenboer Illustrated C# 7 Daniel Solis Cal Schrotenboer SAN JOSE, California, USA Kissimmee, Florida, USA ISBN-13 (pbk): 978-1-4842-3287-3 ISBN-13 (electronic): 978-1-4842-3288-0 https://doi.org/10.1007/978-1-4842-3288-0 Library of Congress Control Number: 2018934213 Copyright © 2018 by Daniel Solis and Cal Schrotenboer This work is subject to copyright. All rights are reserved by the Publisher, whether the whole or part of the material is concerned, specifically the rights of translation, reprinting, reuse of illustrations, recitation, broadcasting, reproduction on microfilms or in any other physical way, and transmission or information storage and retrieval, electronic adaptation, computer software, or by similar or dissimilar methodology now known or hereafter developed. Trademarked names, logos, and images may appear in this book. Rather than use a trademark symbol with every occurrence of a trademarked name, logo, or image we use the names, logos, and images only in an editorial fashion and to the benefit of the trademark owner, with no intention of infringement of the trademark. The use in this publication of trade names, trademarks, service marks, and similar terms, even if they are not identified as such, is not to be taken as an expression of opinion as to whether or not they are subject to proprietary rights. While the advice and information in this book are believed to be true and accurate at the date of publication, neither the authors nor the editors nor the publisher can accept any legal responsibility for any errors or omissions that may be made. The publisher makes no warranty, express or implied, with respect to the material contained herein. Managing Director, Apress Media LLC: Welmoed Spahr Acquisitions Editor: Gwenan Spearing Development Editor: Laura Berendson Coordinating Editor: Nancy Chen Cover designed by eStudioCalamar Cover image designed by Freepik (www.freepik.com) Distributed to the book trade worldwide by Springer Science+Business Media New York, 233 Spring Street, 6th Floor, New York, NY 10013. Phone 1-800-SPRINGER, fax (201) 348-4505, e-mail [email protected], or visit www.springeronline.com. Apress Media LLC is a California LLC, and the sole member (owner) is Springer Science + Business Media Finance Inc (SSBM Finance Inc). SSBM Finance Inc is a Delaware corporation. For information on translations, please e-mail [email protected], or visit www.apress.com/ rights-permissions. Apress titles may be purchased in bulk for academic, corporate, or promotional use. eBook versions and licenses are also available for most titles. For more information, reference our Print and eBook Bulk Sales web page at www.apress.com/bulk-sales. Any source code or other supplementary material referenced by the author in this book is available to readers on GitHub via the book’s product page, located at www.apress.com/9781484232873. For more detailed information, please visit www.apress.com/source-code. Printed on acid-free paper This book is dedicated to Sian and Galen. —Dan This book is dedicated to Paul, Kristin, and Alison. —Cal Contents About the Authors ������������������������������������������������������������������������������������������������xxvii About the Technical Reviewers ����������������������������������������������������������������������������xxix Acknowledgments ������������������������������������������������������������������������������������������������xxxi Introduction ��������������������������������������������������������������������������������������������������������xxxiii ■ Chapter 1: C# and the �NET Framework �����������������������������������������������������������������1 Before .NET ......................................................................................................................2 Windows Programming in the Late 1990s ..............................................................................................2 Goals for the Next-Generation Platform Services ...................................................................................2 Enter Microsoft .NET ........................................................................................................3 Components of the .NET Framework ......................................................................................................3 An Improved Programming Environment ................................................................................................4 Compiling to the Common Intermediate Language ..........................................................7 Compiling to Native Code and Execution..........................................................................8 Overview of Compilation and Execution .................................................................................................9 The Common Language Runtime ...................................................................................10 The Common Language Infrastructure ...........................................................................11 Important Parts of the CLI .....................................................................................................................12 Review of the Acronyms .................................................................................................13 The Evolution of C# ........................................................................................................14 C# and the Evolution of Windows ...................................................................................15 v ■ Contents ■ Chapter 2: C# and �NET Core ��������������������������������������������������������������������������������17 The .NET Framework Background ..................................................................................18 Why .NET Core (and Xamarin)? ......................................................................................18 Goals of .NET Core ..........................................................................................................19 Multiplatform Support ....................................................................................................20 Rapid Development and Upgrades .................................................................................20 Smaller Application Footprints, Simpler Deployment, and Reduced Versioning Problems .................................................................................20 Open Source Community Support ..................................................................................21 Improved Application Performance ................................................................................21 Fresh Start ......................................................................................................................21 The Development of .NET Core .......................................................................................22 Where Does This Leave the .NET Framework? ...............................................................22 Where Does Xamarin Fit In? ...........................................................................................22 ■ Chapter 3: Overview of C# Programming ������������������������������������������������������������23 A Simple C# Program .....................................................................................................24 More About SimpleProgram ..................................................................................................................25 Identifiers .......................................................................................................................26 Keywords ........................................................................................................................27 Main: The Starting Point of a Program ...........................................................................28 Whitespace .....................................................................................................................28 Statements .....................................................................................................................29 Blocks ...................................................................................................................................................29 Text Output from a Program ...........................................................................................30 Write .....................................................................................................................................................30 WriteLine ..............................................................................................................................................30 The Format String .................................................................................................................................31 Multiple Markers and Values ................................................................................................................33 Formatting Numeric Strings .................................................................................................................34 vi ■ Contents Comments: Annotating the Code ....................................................................................40 More About Comments .........................................................................................................................41 Documentation Comments ...................................................................................................................41 Summary of Comment Types ................................................................................................................42 ■ Chapter 4: Types, Storage, and Variables ������������������������������������������������������������43 A C# Program Is a Set of Type Declarations ...................................................................44 A Type Is a Template .......................................................................................................45 Instantiating a Type ........................................................................................................45 Data Members and Function Members ..........................................................................46 Types of Members ................................................................................................................................46 Predefined Types ............................................................................................................47 More About the Predefined Types .........................................................................................................48 User-Defined Types.........................................................................................................49 The Stack and the Heap .................................................................................................50 The Stack ..............................................................................................................................................50 The Heap ..............................................................................................................................................51 Value Types and Reference Types ..................................................................................52 Storing Members of a Reference Type Object ......................................................................................52 Categorizing the C# Types ....................................................................................................................53 Variables .........................................................................................................................54 Variable Declarations ............................................................................................................................54 Multiple-Variable Declarations .............................................................................................................56 Using the Value of a Variable ................................................................................................................56 Static Typing and the dynamic Keyword ........................................................................57 Nullable Types ................................................................................................................57 ■ Chapter 5: Classes: The Basics ����������������������������������������������������������������������������59 Overview of Classes .......................................................................................................60 A Class Is an Active Data Structure ......................................................................................................60 Programs and Classes: A Quick Example .......................................................................61 Declaring a Class ............................................................................................................62 vii ■ Contents Class Members ...............................................................................................................63 Fields ....................................................................................................................................................63 Methods ................................................................................................................................................65 Creating Variables and Instances of a Class ..................................................................66 Allocating Memory for the Data .....................................................................................67 Combining the Steps ............................................................................................................................68 Instance Members ..........................................................................................................69 Access Modifiers ............................................................................................................70 Private and Public Access .....................................................................................................................70 Accessing Members from Inside the Class ....................................................................73 Accessing Members from Outside the Class ..................................................................74 Putting It All Together .....................................................................................................75 ■ Chapter 6: Methods ���������������������������������������������������������������������������������������������77 The Structure of a Method .............................................................................................78 Code Execution in the Method Body ...............................................................................79 Local Variables ...............................................................................................................80 Type Inference and the var Keyword ....................................................................................................81 Local Variables Inside Nested Blocks ...................................................................................................82 Local Constants ..............................................................................................................83 Flow of Control ...............................................................................................................84 Method Invocations ........................................................................................................85 Return Values .................................................................................................................86 The Return Statement and Void Methods .......................................................................88 Local Functions ..............................................................................................................90 Parameters .....................................................................................................................91 Formal Parameters ...............................................................................................................................91 Actual Parameters ................................................................................................................................92 Value Parameters ...........................................................................................................94 Reference Parameters ....................................................................................................97 viii ■ Contents Reference Types As Value and Reference Parameters .................................................100 Output Parameters .......................................................................................................104 Parameter Arrays..........................................................................................................108 Method Invocation ..............................................................................................................................109 Arrays As Actual Parameters ..............................................................................................................112 Summary of Parameter Types ......................................................................................112 Ref Local and Ref Return .............................................................................................113 Method Overloading .....................................................................................................117 Named Parameters ......................................................................................................118 Optional Parameters .....................................................................................................120 Stack Frames ...............................................................................................................124 Recursion .....................................................................................................................126 ■ Chapter 7: More About Classes �������������������������������������������������������������������������129 Class Members .............................................................................................................130 Order of Member Modifiers ..........................................................................................130 Instance Class Members ..............................................................................................132 Static Fields ..................................................................................................................133 Accessing Static Members from Outside the Class .....................................................134 Example of a Static Field ....................................................................................................................135 Lifetimes of Static Members ..............................................................................................................136 Static Function Members .............................................................................................137 Other Static Class Member Types .................................................................................138 Member Constants .......................................................................................................139 Constants Are Like Statics ............................................................................................140 Properties .....................................................................................................................141 Property Declarations and Accessors .................................................................................................142 A Property Example ............................................................................................................................143 Using a Property .................................................................................................................................144 Properties and Associated Fields .......................................................................................................145 ix ■ Contents Performing Other Calculations............................................................................................................147 Read-Only and Write-Only Properties .................................................................................................148 Properties vs. Public Fields ................................................................................................................148 An Example of a Computed, Read-Only Property ...............................................................................149 Automatically Implemented Properties—Auto-properties .................................................................150 Static Properties .................................................................................................................................151 Instance Constructors ..................................................................................................152 Constructors with Parameters ............................................................................................................153 Default Constructors ...........................................................................................................................154 Static Constructors .......................................................................................................155 Example of a Static Constructor .........................................................................................................156 Object Initializers ..........................................................................................................157 Destructors ...................................................................................................................158 The readonly Modifier ..................................................................................................159 The this Keyword ..........................................................................................................160 Indexers ..............................................................................................................................................162 What Is an Indexer? ............................................................................................................................163 Indexers and Properties ......................................................................................................................163 Declaring an Indexer ...........................................................................................................................164 The Indexer set Accessor....................................................................................................................165 The Indexer get Accessor ...................................................................................................................166 More About Indexers ...........................................................................................................................166 Declaring the Indexer for the Employee Example ...............................................................................167 Another Indexer Example....................................................................................................................168 Indexer Overloading ............................................................................................................................169 Access Modifiers on Accessors ....................................................................................170 Partial Classes and Partial Types ..................................................................................171 Partial Methods ............................................................................................................173 x