The C# Player's Guide 5th Edition PDF

Document Details

2022

RB Whitaker

Tags

C# programming Object-Oriented Programming .NET computer programming

Summary

This is a C# programming textbook covering the fundamentals and advanced features of the language. It includes numerous examples, exercises, and knowledge check questions. The book covers basic programming concepts, object-oriented programming, advanced features like asynchronous programming and compiler errors, as well as complete game projects.

Full Transcript

It is illegal to redistribute this digital book. Please do not share this file via email, websites, or any other means. Be mindful about where you store it and who might gain access to it. The digital format of this book is only legally distributed via https://gumroad.com/l/oKNdk. I...

It is illegal to redistribute this digital book. Please do not share this file via email, websites, or any other means. Be mindful about where you store it and who might gain access to it. The digital format of this book is only legally distributed via https://gumroad.com/l/oKNdk. If you have received this book through any other means, please report it to [email protected]. You may make any copies you need for your own personal use. 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 author and publisher were aware of those claims, those designations have been printed with initial capital letters or in all capitals. The author and publisher of this book have made every effort to ensure that this book’s information was correct at press time. However, the author and publisher do not assume and hereby disclaim any liability to any party for any loss, damage, or disruption caused by errors or omissions, whether such errors or omissions result from negligence, accident, or any other cause. Copyright © 2012-2022 by RB Whitaker All rights reserved. No part of this book may be reproduced or transmitted in any form or by any means, electronic or mechanical, including photocopying, recording, or by any information storage and retrieval system, without written permission from the author, except for the inclusion of brief quotations in a review. For information regarding permissions, write to: RB Whitaker [email protected] ISBN-13: 978-0-9855801-5-5 Starbound Software Part 1: The Basics ✓ Page Name XP 10 Knowledge Check - C# 25 14 Install Visual Studio 75 19 Hello, World! 50 24 What Comes Next 50 24 The Makings of a Programmer 50 26 Consolas and Telim 50 31 The Thing Namer 3000 100 37 Knowledge Check - Variables 25 45 The Variable Shop 100 45 The Variable Shop Returns 50 48 Knowledge Check - Type System 25 53 The Triangle Farmer 100 56 The Four Sisters and the Duckbear 100 57 The Dominion of Kings 100 68 The Defense of Consolas 200 75 Repairing the Clocktower 100 78 Watchtower 100 82 Buying Inventory 100 83 Discounted Inventory 50 88 The Prototype 100 89 The Magic Cannon 100 94 The Replicator of D’To 100 95 The Laws of Freach 50 106 Taking a Number 100 107 Countdown 100 123 Knowledge Check - Memory 25 124 Hunting the Manticore 250 Part 2: Object-Oriented Programming ✓ Page Name XP 131 Knowledge Check - Objects 25 135 Simula’s Test 100 143 Simula’s Soups 100 153 Vin Fletcher’s Arrows 100 162 Vin’s Trouble 50 168 The Properties of Arrows 100 173 Arrow Factories 100 191 The Point 75 191 The Color 100 191 The Card 100 192 The Locked Door 100 192 The Password Validator 100 193 Rock-Paper-Scissors 150 194 15-Puzzle 150 194 Hangman 150 195 Tic-Tac-Toe 300 205 Packing Inventory 150 ✓ Page Name XP 209 Labeling Inventory 50 210 The Old Robot 200 217 Robotic Interface 75 225 Room Coordinates 50 231 War Preparations 100 240 Colored Items 100 242 The Fountain of Objects 500 244 Small, Medium, or Large 100 244 Pits 100 244 Maelstroms 100 245 Amaroks 100 245 Getting Armed 100 246 Getting Help 100 249 The Robot Pilot 50 ✓ Page 251 Time in the Cavern 50 Name XP 255 Lists of Commands 75 398 The Great Humanizer 100 403 Knowledge Check - Compiling 25 Part 3: Advanced Features 408 Knowledge Check -.NET 25 413 Altar of Publication 100 ✓ Page Name XP 269 Knowledge Check - Large Programs 25 270 The Feud 75 Part 4: The Endgame ✓ Page 270 Dueling Traditions 100 Name XP 276 Safer Number Crunching 50 419 Core Game: Building Character 300 278 Knowledge Check - Methods 25 420 Core Game: The True Programmer 100 278 Better Random 100 420 Core Game: Actions and Players 300 290 Exepti’s Game 100 421 Core Game: Attacks 200 295 The Sieve 100 421 Core Game: Damage and HP 150 301 Knowledge Check - Events 25 422 Core Game: Death 150 302 Charberry Trees 100 422 Core Game: Battle Series 150 307 Knowledge Check - Lambdas 25 422 Core Game: The Uncoded One 100 307 The Lambda Sieve 50 423 Core Game: The Player Decides 200 315 The Long Game 100 423 Expansion: The Game’s Status 100 324 The Potion Masters of Pattren 150 424 Expansion: Items 200 331 Knowledge Check - Operators 25 424 Expansion: Gear 300 331 Navigating Operand City 100 425 Expansion: Stolen Inventory 200 332 Indexing Operand City 75 426 Expansion: Vin Fletcher 200 332 Converting Directions to Offsets 50 426 Expansion: Attack Modifiers 200 341 Knowledge Check - Queries 25 426 Expansion: Damage Types 200 342 The Three Lenses 100 427 Expansion: Making it Yours ? 349 The Repeating Stream 150 428 Expansion: Restoring Balance 150 359 Knowledge Check - Async 25 359 Asynchronous Random Words 150 360 Many Random Words 50 Part 5: Bonus Levels 365 Uniter of Adds 75 ✓ Page Name XP 366 The Robot Factory 100 441 Knowledge Check - Visual Studio 25 372 Knowledge Check - Unsafe Code 25 446 Knowledge Check - Compiler Errors 25 392 Knowledge Check - Other Features 25 451 Knowledge Check - Debugging 25 397 Colored Console 100 TABLE OF CONTENTS Acknowledgments xix Introduction 1 The Great Game of Programming 1 Book Features 2 I Want Your Feedback 6 An Overview 6 PART 1: THE BASICS 1. The C# Programming Language 9 What is C#? 9 What is.NET? 10 2. Getting an IDE 11 A Comparison of IDEs 11 Installing Visual Studio 13 3. Hello World: Your First Program 15 Creating a New Project 15 A Brief Tour of Visual Studio 17 Compiling and Running Your Program 18 Syntax and Structure 19 Beyond Hello World 24 Compiler Errors, Debuggers, and Configurations 27 4. Comments 29 How to Make Good Comments 30 x TABLE OF CONTENTS 5. Variables 32 What is a Variable? 32 Creating and Using Variables in C# 33 Integers 34 Reading from a Variable Does Not Change It 35 Clever Variable Tricks 35 Variable Names 36 6. The C# Type System 38 Representing Data in Binary 38 Integer Types 39 Text: Characters and Strings 42 Floating-Point Types 43 The bool Type 45 Type Inference 46 The Convert Class and the Parse Methods 47 7. Math 50 Operations and Operators 50 Addition, Subtraction, Multiplication, and Division 51 Compound Expressions and Order of Operations 52 Special Number Values 54 Integer Division vs. Floating-Point Division 54 Division by Zero 55 More Operators 55 Updating Variables 56 Working with Different Types and Casting 58 Overflow and Roundoff Error 60 The Math and MathF Classes 61 8. Console 2.0 63 The Console Class 63 Sharpening Your String Skills 65 9. Decision Making 69 The if Statement 69 The else Statement 73 else if Statements 73 Relational Operators: ==, !=, , = 74 Using bool in Decision Making 75 Logical Operators 76 Nesting if Statements 77 The Conditional Operator 77 10. Switches 79 TABLE OF CONTENTS xi Switch Statements 80 Switch Expressions 81 Switches as a Basis for Pattern Matching 82 11. Looping 84 The while Loop 84 The do/while Loop 86 The for Loop 86 break Out of Loops and continue to the Next Pass 87 Nesting Loops 88 12. Arrays 90 Creating Arrays 91 Getting and Setting Values in Arrays 91 Other Ways to Create Arrays 93 Some Examples with Arrays 94 The foreach Loop 95 Multi-Dimensional Arrays 95 13. Methods 97 Defining a Method 97 Calling a Method 99 Passing Data to a Method 101 Returning a Value from a Method 103 Method Overloading 104 Simple Methods with Expressions 105 XML Documentation Comments 106 The Basics of Recursion 107 14. Memory Management 109 Memory and Memory Management 110 The Stack 110 Fixed-Size Stack Frames 115 The Heap 115 Cleaning Up Heap Memory 122 PART 2: OBJECT-ORIENTED PROGRAMMING 15. Object-Oriented Concepts 129 Object-Oriented Concepts 129 16. Enumerations 132 Enumeration Basics 133 Underlying Types 136 17. Tuples 137 xii TABLE OF CONTENTS The Basics of Tuples 138 Tuple Element Names 139 Tuples and Methods 139 More Tuple Examples 140 Deconstructing Tuples 141 Tuples and Equality 142 18. Classes 144 Defining a New Class 145 Instances of Classes 147 Constructors 148 Object-Oriented Design 153 19. Information Hiding 155 The public and private Accessibility Modifiers 156 Abstraction 159 Type Accessibility Levels and the internal Modifier 160 20. Properties 163 The Basics of Properties 163 Auto-Implemented Properties 166 Immutable Fields and Properties 167 Object Initializer Syntax and Init Properties 168 Anonymous Types 169 21. Static 170 Static Members 170 Static Classes 173 22. Null References 174 Null or Not? 175 Checking for Null 176 23. Object-Oriented Design 178 Requirements 179 Designing the Software 180 Creating Code 185 How to Collaborate 187 Baby Steps 189 24. The Catacombs of the Class 190 The Five Prototypes 190 Object-Oriented Design 193 Tic-Tac-Toe 195 25. Inheritance 197 Inheritance and the object Class 198 Choosing Base Classes 200 TABLE OF CONTENTS xiii Constructors 201 Casting and Checking for Types 203 The protected Access Modifier 204 Sealed Classes 204 26. Polymorphism 206 Abstract Methods and Classes 208 New Methods 209 27. Interfaces 211 Defining Interfaces 212 Implementing Interfaces 213 Interfaces and Base Classes 214 Explicit Interface Implementations 214 Default Interface Methods 215 28. Structs 218 Memory and Constructors 219 Classes vs. Structs 220 Built-In Type Aliases 224 Boxing and Unboxing 225 29. Records 227 Records 227 Advanced Scenarios 229 Struct- and Class-Based Records 230 When to Use a Record 231 30. Generics 232 The Motivation for Generics 232 Defining a Generic Type 235 Generic Methods 237 Generic Type Constraints 237 The default Operator 239 31. The Fountain of Objects 241 The Main Challenge 242 Expansions 244 32. Some Useful Types 247 The Random Class 248 The DateTime Struct 249 The TimeSpan Struct 250 The Guid Struct 251 The List Class 252 The IEnumerable Interface 255 The Dictionary Class 256 xiv TABLE OF CONTENTS The Nullable Struct 258 ValueTuple Structs 258 The StringBuilder Class 259 PART 3: ADVANCED TOPICS 33. Managing Larger Programs 263 Using Multiple Files 263 Namespaces and using Directives 264 Traditional Entry Points 268 34. Methods Revisited 271 Optional Arguments 271 Named Arguments 272 Variable Number of Parameters 272 Combinations 273 Passing by Reference 273 Deconstructors 276 Extension Methods 277 35. Error Handling and Exceptions 280 Handling Exceptions 281 Throwing Exceptions 283 The finally Block 284 Exception Guidelines 285 Advanced Exception Handling 288 36. Delegates 291 Delegate Basics 291 The Action, Func, and Predicate Delegates 294 MulticastDelegate and Delegate Chaining 295 37. Events 296 C# Events 296 Event Leaks 300 EventHandler and Friends 300 Custom Event Accessors 301 38. Lambda Expressions 303 Lambda Expression Basics 303 Lambda Statements 305 Closures 306 39. Files 308 The File Class 308 String Manipulation 310 File System Manipulation 312 TABLE OF CONTENTS xv Other Ways to Access Files 313 40. Pattern Matching 316 The Constant Pattern and the Discard Pattern 317 The Monster Scoring Problem 317 The Type and Declaration Patterns 318 Case Guards 319 The Property Pattern 319 Relational Patterns 320 The and, or, and not Patterns 321 The Positional Pattern 321 The var Pattern 322 Parenthesized Patterns 322 Patterns with Switch Statements and the is Keyword 322 Summary 323 41. Operator Overloading 325 Operator Overloading 326 Indexers 327 Custom Conversions 329 42. Query Expressions 333 Query Expression Basics 334 Method Call Syntax 336 Advanced Queries 338 Deferred Execution 340 LINQ to SQL 341 43. Threads 343 The Basics of Threads 343 Using Threads 344 Thread Safety 347 44. Asynchronous Programming 351 Threads and Callbacks 352 Using Tasks 353 Who Runs My Code? 356 Some Additional Details 358 45. Dynamic Objects 361 Dynamic Type Checking 362 Dynamic Objects 362 Emulating Dynamic Objects with Dictionaries 363 Using ExpandoObject 363 Extending DynamicObject 364 When to Use Dynamic Object Variations 365 xvi TABLE OF CONTENTS 46. Unsafe Code 367 Unsafe Contexts 368 Pointer Types 368 Fixed Statements 369 Stack Allocations 370 Fixed-Size Arrays 370 The sizeof Operator 370 The nint and nuint Types 371 Calling Native Code with Platform Invocation Services 371 47. Other Language Features 373 Iterators and the yield Keyword 374 Constants 375 Attributes 376 Reflection 378 The nameof Operator 379 Nested Types 379 Even More Accessibility Modifiers 380 Bit Manipulation 380 using Statements and the IDisposable Interface 384 Preprocessor Directives 385 Command-Line Arguments 387 Partial Classes 387 The Notorious goto Keyword 388 Generic Covariance and Contravariance 389 Checked and Unchecked Contexts 391 Volatile Fields 392 48. Beyond a Single Project 393 Outgrowing a Single Project 393 NuGet Packages 396 49. Compiling in Depth 399 Hardware 399 Assembly 401 Programming Languages 401 Instruction Set Architectures 402 Virtual Machines and Runtimes 402 50..NET 404 The History of.NET 404 The Components of.NET 405 Common Infrastructure 405 Base Class Library 406 App Models 407 TABLE OF CONTENTS xvii 51. Publishing 409 Build Configurations 409 Publish Profiles 410 PART 4: THE ENDGAME 52. The Final Battle 417 Overview 418 Core Challenges 419 Expansions 423 53. Into Lands Uncharted 429 Keep Learning 429 Where Do I Go to Get Help? 430 Parting Words 431 PART 5: BONUS LEVELS A. Visual Studio 435 Windows 435 The Options Dialog 441 B. Compiler Errors 442 Code Problems: Errors, Warnings, and Messages 442 How to Resolve Compiler Errors 443 Common Compiler Errors 445 C. Debugging Your Code 447 Print Debugging 448 Using a Debugger 448 Breakpoints 449 Stepping Through Code 450 Breakpoint Conditions and Actions 451 Glossary 452 Index 468 ACKNOWLEDGMENTS It is hard to separate the 5th Edition from the 4th Edition when it comes to acknowledgments. The 4th Edition kept the bones of earlier editions but otherwise was a complete rewrite (twice!). Despite being 20 years old, C# 9 and 10 have changed the language in meaningful, exciting, and fundamental ways. Indeed, most random code you find on the Internet now looks like “old” C# code. These recent changes are somehow both tiny and game-changing. I don’t have a great way to measure, but I’ve often guessed that the 5th Edition is 98% the same as the 4th Edition. I might have even called this edition 4.1 if that were that a thing books did. Yet that last 2%, primarily reflecting C# 10 changes and the fast-evolving language, was enough to feel a new edition was not only helpful but necessary. I want to thank the hundreds of people who joined Early Access for 4th and 5th Editions and the readers who have joined the book’s Discord server. The discussions I have had with you have changed this book for the better in a thousand different ways. With so many involved, I cannot thank everyone by name, though you all deserve it for your efforts. Having said that, UD Simon deserves special mention for providing me with a tsunami of suggestions and error reports week after week, rivaling the combined total of all other Early Access readers. The book is immeasurably better because of your collective efforts. I also need to thank my family. My parents’ confidence and encouragement to do my best have caused me to do things I could never have done without them. Most of all, I want to thank my beautiful wife, who was there to lift my spirits when the weight of writing a book was unbearable, who read through my book and gave honest, thoughtful, and creative feedback and guidance. She has been patient with me as I’ve done five editions of this book over the years. Without her, this book would still be a random scattering of files buried in some obscure folder on my computer, collecting green silicon-based mold. I owe all of you my sincerest gratitude. -RB Whitaker INTRODUCTION THE GREAT GAME OF PROGRAMMING I have a firmly held personal belief, grown from decades of programming: in a very real sense, programming is a game. At least, it can be like playing a game with the right mindset. For me, spending a few hours programming—crafting code that bends these amazing computational devices to my will and creating worlds of living software—is entertaining and rewarding. It competes with delving into the Nether in Minecraft, snatching the last Province card in Dominion, or taking down a reaper in Mass Effect. I don’t mean that programming is mindless entertainment. It is rarely that. Most of your time is spent puzzling out the right next step or figuring out why things aren’t working as you expected. But part of what makes games engaging is that they are challenging. You have to work for it. You apply creativity and explore possibilities. You practice and gain abilities that help you win. You'll be in good shape if you approach programming with this same mindset because programming requires this same set of skills. Some days, it will feel like you are playing Flappy Bird, Super Meat Boy, or Dark Souls—all notoriously difficult games—but creating software is challenging in all the right ways. The “game” of programming is a massively multiplayer, open-world sandbox game with role- playing elements. By that, I mean: Massively multiplayer: While you may tackle specific problems independently, you are never alone. Most programmers are quick to share their knowledge and experience with others. This book and the Internet ensure you are not alone in your journey. An open-world sandbox game: You have few constraints or limitations; you can build what, when, and how you want. Role-playing elements: With practice, learning, and experience, you get better in the skills and tools you work with, going from a lowly Level 1 beginner to a master, sharpening your skills and abilities as you go. If programming is to be fun or rewarding, then learning to program must also be so. Rare is the book that can make learning complex technical topics anything more than tedious. This book attempts to do just that. If a spoonful of sugar can help the medicine go down, then there 2 LEVEL 1 INTRODUCTION must be some blend of eleven herbs and spices that will make even the most complex technical topic have an element of fun, challenge, and reward. Over the years, strategy guides, player handbooks, and player’s guides have been made for popular games. These guides help players learn and understand the game world and the challenges they will encounter. They provide time-saving tips and tricks and help prevent players from getting stuck anywhere for too long. This book attempts to be that player’s guide for the Great Game of Programming in C#. This book skips the typical business-centric examples found in other books in favor of samples with a little more spice. Many are game-related, and many of the hands-on challenges involve building small games or slices of games. This makes the journey more entertaining and exciting. While C# is an excellent language for game development, this book is not specifically a C# game programming book. You will undoubtedly come away with ideas to try if that’s the path you choose, but this book is focused on becoming skilled with the C# language so that you can use it to build any type of program, not just games. (Most professional programmers make business-centric applications, web apps, and smartphone apps.) This book focuses on console applications. Console applications are those text-based programs where the computer receives text input from the user and displays text responses in the stereotypical white text on a black background window. We’ll learn some things to make console applications more colorful and exciting, but console applications are, admittedly, not the most exciting type of application. Why not use something more exciting? The main reason is that regardless of whether you want to build games, smartphone apps, web apps, or desktop apps, the starting points in those worlds already expect you to know much about C#. For example, I just looked over the starter code for a certain C# game development framework. It demands you already know how to use advanced topics covered in Level 25 (inheritance), Level 26 (polymorphism), and Level 30 (generics) just to get started! While some people successfully dive in and stay afloat, it is usually wiser to build up your swimming skills in a lap pool before trying to swim across the raging ocean. Starting from the basics gives you a better foundation. After building this foundation, learning how to make specific application types will go much more smoothly. Few will be satisfied with just console applications, but spending a few weeks covering the basics before moving on will make the learning process far easier. BOOK FEATURES Creating a fun and rewarding book (or at least not a dull and useless one) means adding some features that most programming books do not have. Let’s look at a few of these so that you know what to expect. Speedruns At the start of each level (chapter) is a Speedrun section that outlines the key points described in the level. It is not a substitute for going through the whole level in detail but is helpful in a handful of situations: 1. You’re reviewing the material and want a reminder of the key points. 2. You are skimming to see if some level has information that you will need soon. 3. You are trying to remember which level covered some particular topic. BOOK FEATURES 3 Challenges and Boss Battles Scattered throughout the book are hands-on challenges that give you a specific problem to work on. These start small early in the book, but some of the later ones are quite large. Each of these challenges is marked with the following icon: When a challenge is especially tough, it is upgraded to a Boss Battle, shown by the icon below: Boss Battles are sometimes split across multiple parts to allow you to work through them one step at a time. I strongly recommend that you do these challenges. You don’t beat a game by reading the player’s guide. You don’t learn to program by reading a book. You will only truly learn if you sit down and program. I also recommend you do these challenges as you encounter them instead of reading ten chapters and returning to them. The read a little, program a little model is far better at helping you learn fast. I also feel that these challenges should not be the only things you program as you learn, especially if you are relatively new to programming. Half of your programming time should come from these challenges and the rest from your own imagination. Working on things of your own invention will be more exciting to you. But also, when you are in that creative mindset, you mentally explore the programming world better. You start to think about how you can apply the tools you have learned in new situations, rather than being told, “Go use this tool over here in this specific way.” As you do that, keep in mind the size of the challenges you are inventing for yourself. If you are learning how to draw, you don’t go find millennia-old chapel ceilings to paint (or at least you don’t expect it to turn out like the Sistine Chapel). Aim for things that push your limits a little but aren’t intimidating. Keep in mind that everything is a bit harder than you initially expect. And don’t be afraid to dive in and make a mess. Continuing the art analogy, you aren't learning if you don’t have a few garbage drawings in your sketchbook. Not every line of code you write will be a masterpiece. You have permission to write strange, ugly, and awkward code. If these specific challenges are not your style, then skip them. But substitute them with something else. You will learn little if you don’t sit down and write some code. When a challenge contains a Hint, these are suggestions or possibilities, not things you must do. If you find a different path that works, go for it. Some challenges also include things labeled Answer this question. I recommend writing out your answer. (Comments, covered in Level 4, could be a good approach.) Our brains like to tell us it understands something without proving it does. We mentally skip the proof, often to our detriment. Writing it out ensures we know it. These questions usually only take a few seconds to answer. I have posted my answers to these challenges on the book’s website, described later in this introduction. If you want a hint or compare answers, you can review what I did. Just because our solutions are different doesn’t make yours bad or wrong. I make plenty of my own 4 LEVEL 1 INTRODUCTION mistakes, have my own preferences for the various tools in the language, and have also been programming in C# for a long time. As long as you have a working solution, you’re doing fine. Knowledge Checks Some levels in this book focus on conceptual topics that are not well-tested by a programming problem. In these cases, instead of a Challenge problem, these levels will have a Knowledge Check, containing a quiz with true/false, multiple-choice, and short answer questions. The answers are immediately below the Knowledge Check, so you can see if you learned the key points right away. These are marked with the knowledge scroll icon below: Experience Points and Levels Since this book is a player’s guide, I’ve attempted to turn the learning process into a game. Each Challenge and Knowledge Check section is marked in the top right with experience points (written as XP, as most games do) that you earn by completing the challenge. When you complete a challenge, you can claim the XP associated with it and add it to your total. Towards the front of this book, after the title page and the map, is an XP Tracker. You can use this to track your progress, check off challenges as you complete them, and mark off your progress as you go. You can also get extra copies of the XP Tracker on the book’s website (described below) if you do not want to write in your book, have a digital copy, or have a used copy where somebody else has already marked it. As you collect XP, you will accumulate enough points to level up from Level 1 to Level 10. If you reach Level 10, you will have completed nearly every challenge in this book and should have an excellent grasp of C# programming. The XP assigned to each challenge is not random. Easier challenges have fewer points; more demanding challenges are worth more XP. While measuring difficulty is somewhat subjective, you can generally count on spending more time on challenges with more points and will gain a greater reward for it. Narratives and the Plot The challenges form a loose storyline that has you, the (soon to be) Master Programmer journeying through a land that has been stripped of the ability to program by the malevolent, shadowy, and amorphous Uncoded One. Using your growing C# programming skills, you will be able to help the land’s inhabitants, fend off the Uncoded One’s onslaught, and eventually face the Uncoded One in a final battle at the end of the book. Even if this plot is not attractive to you, the challenges are still worth doing. Feel free to ignore the book-long storytelling if it isn’t helpful for you. While much of the book’s “plot” is revealed in the Challenge descriptions themselves, there were places where it felt shoehorned. Narrative sections supplement the descriptions in the challenges but otherwise have no purpose beyond advancing this book-long plot. These are marked with the icon below: BOOK FEATURES 5 If you are ignoring the plot, you can skip these sections. They do not contain information that helps you be a better C# programmer. Side Quests While everything in this book is worth knowing (skilled C# programmers know all of it), some sections are more important than others. Sections that may be skipped in your first pass through this book are marked as Side Quests, indicated with the following icon: These often deal with situations that are less common or less impactful. If you’re pressed for time, these sections are better to skip than the rest. However, I recommend returning to them later if you don’t read them the first time around. Glossary Programmers have a mountain of unique jargon and terminology. Beyond learning a new programming language, understanding this jargon is a second massive challenge for new programmers. To help you with this undertaking, I have carefully defined new concepts within the book as they arise and collected all of these new words and concepts into a glossary at the back of the book. Only the lucky few will remember all such words from seeing it defined once. Use the glossary to refresh your mind on any term you don’t remember well. The Website This book has a website associated with it, which has a lot of supporting content: https:// csharpplayersguide.com. Some of the highlights are below: https://csharpplayersguide.com/solutions. Contains my solutions to all the Challenge sections in this book. My answer is not necessarily more correct than yours, but it can give you some thoughts on a different way to solve the problem and perhaps some hints on how to progress if you are stuck. This also contains more thorough explanations for all of the Knowledge Checks in the book. https://csharpplayersguide.com/errata. This page contains errata (errors in the book) that have been reported to clarify what was meant. If you notice something that seems wrong or inconsistent, you may find a correction here. http://csharpplayersguide.com/articles. This page contains a collection of articles that add to this book’s content. They often cover more in-depth information beyond what I felt is reasonable to include in this book or answer questions readers have asked me. In a few places in this book, I call out articles with more information for the curious. Discord This book has an active Discord server where you can interact with me and other readers to discuss the book, ask questions, report problems, and get feedback on your solutions to the challenges. Go to https://csharpplayersguide.com/discord to see how to join the server. This server is a guildhall where you can rest from your travels and discuss C# with others on a similar journey as you. 6 LEVEL 1 INTRODUCTION I WANT YOUR FEEDBACK I depend on readers like you to help me see how to make the book better. This book is much better because past readers helped me know what parts were good and bad. Naturally, I’d love to hear that you loved the book. But I need constructive criticism too. If there is a challenge that was too hard, a typo you found, a section that wasn’t clear, or even that you felt an entire level or the whole book was bad, I want to hear it. I have gone to great lengths to make this book as good as possible, but with your help, I can make it even better for those who follow in our footsteps. Don’t hesitate to reach out to me, whether your feedback is positive or negative! I have many ways that you can reach out to me. Go to https://csharpplayersguide.com/ contact to find a way that works for you. AN OVERVIEW Let’s take a peek at what lies ahead. This book has five major parts: Part 1—The Basics. This first part covers many of the fundamental elements of C# programming. It focuses on procedural programming, including storing data, picking and choosing which lines of code to run, and creating reusable chunks of code. Part 2—Object-Oriented Programming. C# uses an approach called object-oriented programming to help you break down a large program into smaller pieces that are each responsible for a little slice of the whole program. These tools are essential as you begin building bigger programs. Part 3—Advanced Topics. While Parts 1 and 2 deal with the most critical elements of the C# language, there are various other language features that are worth knowing. This part consists of mostly independent topics. You can jump around and learn the ones you feel are most important to you (or skip them all entirely, for a while). In some ways, you could consider all of Part 3 to be a big Side Quest, though you will be missing out on some cool C# features if you skip it all. Part 4—The Endgame. While hands-on challenges are scattered throughout the book, Part 4 consists of a single, extensive, final program that will test the knowledge and skills that you have learned. It will also wrap up the book, pointing you toward Lands Uncharted and where you might go after finishing this book. Part 5—Bonus Levels. The end of the book contains a few bonus levels that guide you on what to do when you don’t know what else to do—dealing with compiler errors and debugging your code. The glossary and index are also back here at the end of the book. Please do not feel like you must read this book cover to cover to get value from it. If you are new to programming, I recommend a slow, careful pace through Parts 1 and 2, skipping the Side Quests and only advancing when you feel comfortable taking the next step. After Part 2, you might continue your course through the advanced features of Part 3, or you might also choose to skim it to get a flavor for what else C# offers without going into depth. Even if you skim or skip Part 3, you can still attempt the Final Battle in Part 4. If you’re making consistent progress and getting good practice, it doesn’t matter if your progress feels slow. If you are an experienced programmer, you will likely be able to race through Part 1, slow down only a little in Part 2 as you learn how C# does object-oriented programming, and then spend most of your time in Part 3, learning the things that make C# unique. Adapt the journey however you see fit. It is your book and your adventure! Part 1 The Basics The world of C# programming lies in front of you, waiting to be explored. In Part 1, we begin our adventure and learn the basics of programming in C#: Learn what C# and.NET are (Level 1). Install tools to allow us to program in C# (Level 2). Write our first few programs and learn the basic ingredients of a C# program (Level 3). Annotate your code with comments (Level 4). Store data in variables (Level 5). Understand the type system (Levels 6). Do basic math (Level 7). Get input from the user (Level 8). Make decisions (Levels 9 and 10). Run code more than once in loops (Level 11). Make arrays, which contain multiple pieces of data (Level 12). Make methods, which are named, packaged, reusable bits of code (Level 13). Understand how memory is used in C# (Level 14). LEVEL 1 THE C# PROGRAMMING LANGUAGE Speedrun C# is a general-purpose programming language. You can make almost anything with it. C# runs on.NET, which is many things: a runtime that supports your program, a library of code to build upon, and a set of tools to aid in constructing programs. Computers are amazing machines, capable of running billions of instructions every second. Yet computers have no innate intelligence and do not know which instructions will solve a problem. The people who can harness these powerful machines to solve meaningful problems are the wizards of the computing world we call programmers. Humans and computers do not speak the same language. Human language is imprecise and open to interpretation. The binary instructions computers use, formed from 1’s and 0’s, are precise but very difficult for humans to use. Programming languages bridge the two—precise enough for a computer to run but clear enough for a human to understand. WHAT IS C#? There are many programming languages out there, but C# is one of the few that is both widely used and very loved. Let’s talk about some of its key features. C# is a general-purpose programming language. Some languages solve only a specific type of problem. C# is designed to solve virtually any problem equally well. You can use it to make games, desktop programs, web applications, smartphone apps, and more. However, C# is at its best when building applications (of any sort) with it. You probably wouldn’t write a new operating system or device driver with it (though both have been done). C# strikes a balance between power and ease of use. Some languages give the programmer more control than C#, but with more ways to go wrong. Other languages do more to ensure bad things can’t happen by removing some of your power. C# tries to give you both power and ease of use and often manages to do both but always strikes a balance between the two when needed. 10 LEVEL 1 THE C# PROGRAMMING LANGUAGE C# is a living language. It changes over time to adapt to a changing programming world. Programming has changed significantly in the 20 years since it was created. C# has evolved and adapted over time. At the time of publishing, C# is on version 10.0, with new major updates every year or two. C# is in the same family of languages as C, C++, and Java, meaning that C# will be easier to pick up if you know any of those. After learning C#, learning any of those will also be easier. This book sometimes points out the differences between C# and these other languages for readers who may know them. C# is a cross-platform language. It can run on every major operating system, including Windows, Linux, macOS, iOS, and Android. This next paragraph is for veteran programmers; don’t worry if none of this makes sense. (Most will make sense after this book.) C# is a statically typed, garbage collected, object- oriented programming language with imperative, functional, and event-driven aspects. It also allows for dynamic typing and unmanaged code in small doses when needed. WHAT IS.NET? C# is built upon a thing called.NET (pronounced “dot net”)..NET is often called a framework or platform, but.NET is the entire ecosystem surrounding C# programs and the programmers that use it. For example,.NET includes a runtime, which is the environment your C# program runs within. Figuratively speaking, it is like the air your program breathes and the ground it stands on as it runs. Every programming language has a runtime of one kind or another, but the.NET runtime is extraordinarily capable, taking a lot of burden off of you, the programmer..NET also includes a pile of code that you can use in your program directly. This collection is called the Base Class Library (BCL). You can think of this like mission control supporting a rocket launch: a thousand people who each know their specific job well, ready to jump in and support the primary mission (your code) the moment they are needed. For example, you won’t have to write your own code to open files or compute a square root because the Base Class Library can do this for you..NET includes a broad set of tools called a Software Development Kit (SDK) that makes programming life easier..NET also includes things to help you build specific kinds of programs like web, mobile, and desktop applications..NET is an ecosystem shared by other programming languages. Aside from C#, the three other most popular languages are Visual Basic, F#, and PowerShell. You could write code in C# and use it in a Visual Basic program. These languages have many similarities because of their shared ecosystem, and I’ll point these out in some cases. Knowledge Check C# 25 XP Check your knowledge with the following questions: 1. True/False. C# is a special-purpose language optimized for making web applications. 2. What is the name of the framework that C# runs on? Answers: (1) False. (2).NET LEVEL 2 GETTING AN IDE Speedrun Programming is complex; you want an IDE to make programming life easier. Visual Studio is the most used IDE for C# programming. Visual Studio Community is free, feature- rich, and recommended for beginners. Other C# IDEs exist, including Visual Studio Code and Rider. Modern-day programming is complex and challenging, but a programmer does not have to go alone. Programmers work with an extensive collection of tools to help them get their job done. An integrated development environment (IDE) is a program that combines these tools into a single application designed to streamline the programming process. An IDE does for programming what Microsoft Word does for word processing or Adobe Photoshop for image editing. Most programmers will use an IDE as they work. There are several C# IDEs to choose from. (Or you can go without one and use the raw tools directly; I don’t recommend that for new programmers.) We will look at the most popular C# IDEs and discuss their strengths and weaknesses in this level. We’ll use an IDE to program in C#. Unfortunately, every IDE is different, and this book cannot cover them all. While this book focuses on the C# language and not a specific IDE, when necessary, this book will illustrate certain tasks using Visual Studio Community Edition. Feel free to use a different IDE. The C# language itself is the same regardless of which IDE you pick, but you may find slight differences when performing a task in the IDE. Usually, the process is intuitive, and if tinkering fails, Google usually knows. A COMPARISON OF IDES There are several notable IDEs that you can choose from. 12 LEVEL 2 GETTING AN IDE Visual Studio Microsoft Visual Studio is the stalwart, tried-and-true IDE used by most C# developers. Visual Studio is older than even C#, though it has grown up a lot since those days. Of the IDEs we discuss here, this is the most feature-rich and capable, though it has one significant drawback: it works on Windows but not Mac or Linux. Visual Studio comes in three different “editions” or levels: Community, Professional, and Enterprise. The Community and Professional editions have the same feature set, while Enterprise has an expanded set with some nice bells and whistles at extra cost. The difference between the Community Edition and the Professional Edition is only in the cost and the license. Visual Studio Community Edition is free but is meant for students, hobbyists, open-source projects, and individuals, even for commercial use. Large companies do not fit into this category and must buy Professional. If you have more than 250 computers, make more than $1 million annually, or have more than five Visual Studio users, you’ll need to pay for Professional. But that’s almost certainly not you right now. Visual Studio Community edition is my recommendation for new C# programmers running on Windows and is what this book uses throughout. Visual Studio Code Microsoft Visual Studio Code is a lightweight editor (not a fully-featured IDE) that works on Windows, Mac, and Linux. Visual Studio Code is free and has a vibrant community. It does not have the same expansive feature set as Visual Studio, and in some places, the limited feature set is harsh; you sometimes have to run commands on the command line. If you are used to command-line interfaces, this cost is low. But if you’re new to programming, it may feel alien. Visual Studio Code is probably your best bet if Visual Studio isn’t an option for you (Linux and Mac, for example), especially if you have experience using the command line. Visual Studio Code can also run online (vscode.dev), but as of right now, you can’t run your code. (Except by purchasing a codespace via github.com.) Perhaps this limitation will be fixed someday soon. Visual Studio for Mac Visual Studio for Mac is a separate IDE for C# programming that works on Mac. While it shares its name with Visual Studio, it is a different product with many notable differences. Like Visual Studio (for Windows), this has Community, Professional, and Enterprise editions. If you are on a Mac, this IDE is worth considering. JetBrains Rider The only non-Microsoft IDE on this list is the Rider IDE from JetBrains. Rider is comparatively new, but JetBrains is very experienced at making IDEs for other languages. Rider does not have a free tier; the cheapest option is about $140 per year. But it is both feature-rich and cross- platform. If you have the money to spend, this is a good choice on any operating system. Other IDEs There are other IDEs out there, but most C# programmers use one of the above. Other IDEs tend to be missing lots of features, aren’t well supported, and have less online help and documentation. But if you find another IDE that you enjoy, go for it. INSTALLING VISUAL STUDIO 13 Online Editors There are a handful of online C# editors that you can use to tinker with C# without downloading tools. These have certain limitations and often do not keep up with the current language version. Still, you may find these useful if you just want to experiment without a huge commitment. An article on the book’s website (csharpplayersguide.com/articles/online- editors) points out some of these. No IDE You do not need an IDE to program in C#. If you are a veteran programmer, skilled at using the command line, and accustomed to patching together different editors and scripts, you can skip the IDE. I do not recommend this approach for new programmers. It is a bit like building your car from parts before you can drive it. For the seasoned mechanic, this may be part of the enjoyment. Everybody else needs something that they can hop in and go. The IDEs above are in that category. Working without an IDE requires using the dotnet command-line tool to create, compile, test, and package your programs. Even if you use an IDE, you may still find the dotnet tool helpful. (If you use Visual Studio Code, you will need to use it occasionally.) But if you are new to programming, start with an IDE and learn the basics first. INSTALLING VISUAL STUDIO This book’s focus is the C# language itself, but when I need to illustrate a task in an IDE, this book uses Visual Studio Community Edition. The Professional and Enterprise Editions should be identical. Other IDEs are usually similar, but you will find differences. Visual Studio Code is popular enough that I posted an article on the book’s website illustrating how to get started with it: https://csharpplayersguide.com/articles/visual-studio-code. You can download Visual Studio Community Edition from https://visualstudio.microsoft. com/downloads. You will want to download Visual Studio 2022 or newer to use all of the features in this book. Note that this will download the Visual Studio Installer rather than Visual Studio itself. The Visual Studio Installer lets you customize which components Visual Studio has installed. Anytime you want to tweak the available features, you will rerun the installer and make the desired changes. As you begin installing Visual Studio, it will ask you which components to include: 14 LEVEL 2 GETTING AN IDE With everything installed, Visual Studio is a lumbering, all-powerful behemoth. You do not need all possible features of Visual Studio. In fact, for this book, we will only need a small slice of what Visual Studio offers. You can install anything you find interesting, but there is only one item you must install for the code in this book. On the Workloads tab, find the one called.NET desktop development and click on it to enable it. If you forget to do this, you can always re-run the Visual Studio Installer and change what components you have installed. Warning! Be sure you get the right workload installed. If you don’t, you won’t be able to use all of the C# features described in this book. Once Visual Studio is installed, open it. You may end up with a desktop icon, but you can always find it in the Windows Start Menu under Visual Studio 2022. Visual Studio will ask you to sign in with a Microsoft account, even for the free Community Edition. You don’t need to sign in if you don’t want to, but it does enable a few minor features like synchronizing your settings across multiple devices. If you are installing Visual Studio for the first time, you will also get a chance to pick development settings—keyboard shortcuts and a color theme. I have used the light theme in this book because it looks clearer in print. Many developers like the dark theme. Whatever you pick can be changed later. You know you are done when you make it to the launch screen shown below: Challenge Install Visual Studio 75 XP As your journey begins, you must get your tools ready to start programming in C#. Install Visual Studio 2022 Community edition (or another IDE) and get it ready to start programming. LEVEL 3 HELLO WORLD: YOUR FIRST PROGRAM Speedrun New projects usually begin life by being generated from a template. A C# program starts running in the program’s entry point or main method. A full Hello World program looks like this: Console.WriteLine("Hello, World!"); Statements are single commands for the computer to perform. They run one after the next. Expressions allow you to define a value that is computed as the program runs from other elements. Variables let you store data for use later. Console.ReadLine() retrieves a full line of text that a user types from the console window. Our adventure begins in earnest in this level, as we make our first real programs in C# and learn the basics of the language. We’ll start with a simple program called Hello World, the classic first program to write in any new language. It is the smallest meaningful program we could make. It gives us a glimpse of what the language looks like and verifies that our IDE is installed and working. Hello World is the traditional first program to make, and beginning anywhere else would make the programming gods mad. We don’t want that! CREATING A NEW PROJECT A C# project is a combination of two things. The first is your C# source code—instructions you write in C# for the computer to run. The second is configuration—instructions you give to the computer to help it know how to compile or translate C# code into the binary instructions the computer can run. Both of these live in simple text files on your computer. C# source code files use the.cs extension. A project’s configuration uses the.csproj extension. Because these are both simple text files, we could handcraft them ourselves if needed. But most C# programs are started by being generated from one of several templates. Templates are standard starting points; they help you get the configuration right for specific project types and give you some starting code. We will use a template to create our projects. 16 LEVEL 3 HELLO WORLD: YOUR FIRST PROGRAM You may be tempted to skip over this section, assuming you can just figure it out. Don’t! There are several pitfalls here, so don’t skip this section. Start Visual Studio so that you can see the launch screen below: Click on the Create a new project button on the bottom right. Doing this advances you to the Create a new project page: There are many templates to choose from, and your list might not exactly match what you see above. Choose the C# template called Console Application. Warning! You want the C# project called Console Application. Ensure you aren’t getting the Visual Basic one (check the tags below the description). Also, make sure you aren’t getting the Console Application (.NET Framework) one, which is an older template. If you don’t see this template, re-run the installer and add the right workload. We will always use this Console Application template in this book, but you will use other templates as you progress in the C# world. After choosing the C# Console Application template, press the Next button to advance to a page that lets you enter your new program’s details: A BRIEF TOUR OF VISUAL STUDIO 17 Always give projects a good name. You won’t remember what ConsoleApp12 did in two weeks. For the location, pick a spot that you can find later on. (The default location is fine, but it isn’t a prominent spot, so note where it is.) There is also a checkbox for Place solution and project in the same directory. For small projects, I recommend checking this box. Larger programs (solutions) may be formed from many projects. For those, putting projects in their own directory (folder) under a solution directory makes sense. But for small programs with a single project, it is simpler just to put everything in a single folder. Press the Next button to choose your target framework on the final page: Make sure you pick.NET 6.0 for this book! We will be using many.NET 6 features. You can change it after creation, but it is much easier to get it right in the first place. Once you have chosen the framework, push the Create button to create the project. Warning! Make sure you pick.NET 6.0 (or newer), so you can take advantage of all of the C# features covered in this book. A BRIEF TOUR OF VISUAL STUDIO With a new project created, we get our first glimpse at the Visual Studio window: 18 LEVEL 3 HELLO WORLD: YOUR FIRST PROGRAM Visual Studio is extremely capable, so there is much to explore. This book focuses on programming in C#, not becoming a Visual Studio expert. We won’t get into every detail of Visual Studio, but we’ll cover some essential elements here and throughout the book. Right now, there are three things you need to know to get started. First, the big text editor on the left side is the Code Window or the Code Editor. You will spend most of your time working here. Second, on the right side is the Solution Explorer. That shows you a high-level view of your code and the configuration needed to turn it into working code. You will spend only a little time here initially, but you will use this more as you begin to make larger programs. Third, we will run our programs using the part of the Standard Toolbar shown below: Bonus Level A covers Visual Studio in more depth. You can read that level and the other bonus levels whenever you are ready for it. Even though they are at the end of the book, they don’t require knowing everything else before them. If you’re new to Visual Studio, consider reading Bonus Level A before too long. It will give you a better feel for Visual Studio. Time for a sanity check. If you don’t see code in the Code Window, double click on Program.cs in the Solution Explorer. Inspect the code you see in the Code Window. If you see class Program or static void Main, or if the file has more than a couple of lines of text, you may have chosen the wrong template. Go back and ensure you pick the correct template. If the right template isn’t there, re-run the installer to add the right workload. COMPILING AND RUNNING YOUR PROGRAM Generating a new project from the template has produced a complete program. Before we start dissecting it, let’s run it. The computer’s circuitry cannot run C# code itself. It only runs low-level binary instructions formed out of 1’s and 0’s. So before the computer can run our program, we must transform it into something it can run. This transformation is called compiling, done by a special program called a compiler. The compiler takes your C# code and your project’s configuration and produces the final binary instructions that the computer can run directly. The result is either a.exe or.dll file, which the computer can run. (This is an oversimplification, but it’s accurate enough for now.) SYNTAX AND STRUCTURE 19 Visual Studio makes it easy to compile and then immediately run your program with any of the following: (a) choose Debug > Start Debugging from the main menu, (b) press F5, or (c) push the green start button on the toolbar, shown below: When you run your program, you will see a black and white console window appear: Look at the first line: Hello, World! That’s what our program was supposed to do! (The rest of the text just tells you that the program has ended and gives you instructions on how not to show it in the future. You can ignore that text for now.) Challenge Hello, World! 50 XP You open your eyes and find yourself face down on the beach of a large island, the waves crashing on the shore not far off. A voice nearby calls out, “Hey, you! You’re finally awake!” You sit up and look around. Somehow, opening your IDE has pulled you into the Realms of C#, a strange and mysterious land where it appears that you can use C# programming to solve problems. The man comes closer, examining you. “Are you okay? Can you speak?” Creating and running a “Hello, World!” program seems like a good way to respond. Objectives: Create a new Hello World program from the C# Console Application template, targeting.NET 6. Run your program using any of the three methods described above. SYNTAX AND STRUCTURE Now that we’ve made and run our first C# program, it is time to look at the fundamental elements of all C# programs. We will touch on many topics in this section, but each is covered in more depth later in this book. You don’t need to master it all here. Every programming language has its own distinct structure—its own set of rules that describe how to make a working program in that language. This set of rules is called the language’s syntax. Look in your Code Editor window to find the text shown below: Console.WriteLine("Hello, World!"); 20 LEVEL 3 HELLO WORLD: YOUR FIRST PROGRAM You might also see a line with green text that starts with two slashes (//). That is a comment. We’ll talk about comments in Level 4, but you can ignore or even delete that line for now. We’re going to analyze this one-line program in depth. As short as it is, it reveals a great deal about how C# programming works. Strings and Literals First, the "Hello, World!" part is the displayed text. You can imagine changing this text to get the program to show something else instead. In the programming world, we often use the word string to refer to text for reasons we’ll see later. There are many ways we can work with strings or text, but this is the simplest. This is called a literal, or specifically, a string literal. A literal is a chunk of code that defines some specific value, precisely as written. Any text in double quotes will be a string literal. The quote marks aren’t part of the text. They just indicate where the string literal begins and ends. Later on, we’ll see how to make other types of literals, such as number literals. Identifiers The two other big things in our code are Console and WriteLine. These are known formally as identifiers or, more casually, as names. An identifier allows you to refer to some existing code element. As we build code elements of our own, we will pick names for them as well, so we can refer back to them. Console and WriteLine both refer to existing code elements. Hierarchical Organization Between Console and WriteLine, there is a period (.) character. This is called the member access operator or the dot operator. Code elements like Console and WriteLine are organized hierarchically. Some code elements live inside of other code elements. They are said to be members or children of their container. The dot operator allows us to dig down in the hierarchy, from the big parts to their children. In this book, I will sometimes illustrate this hierarchical organization using a diagram like the one shown below: I’ll refer to this type of diagram as a code map in this book. Some versions of Visual Studio can generate similar drawings, but I usually sketch them by hand if I need one. These code maps can help us see the broad structure of a program, which is valuable. Equally important is that a code map can help us understand when a specific identifier can be used. The compiler must determine which code element an identifier refers to. This process is called name binding. But don’t let that name scare you. It really is as simple as, “When the code says, WriteLine, what exactly is that referring to?” Only a handful of elements are globally available. We can start with Console, but we can’t just use WriteLine on its own. The identifier WriteLine is only available in the context of its container, Console. SYNTAX AND STRUCTURE 21 Classes and Methods You may have noticed that I used a different icon for Console and WriteLine in the code map above. Named code elements come in many different flavors. Specifically, Console is a class, while WriteLine is a method. C# has rules that govern what can live inside other things. For example, a class can have methods as members, but a method cannot have a class as a member. We’ll talk about both methods and classes at great length in this book, but let’s start with some basic definitions to get us started. For now, think of classes as entities that solve a single problem or perform a specific job or role. It is like a person on a team. The entire workload is spread across many people, and each one performs their job and works with others to achieve the overarching goal. The Console class’s job is to interact with the console window. It does that well, but don’t ask it to do anything else—it only knows how to work with the console window. Classes are primarily composed of two things: (1) the data they need to do their job and (2) tasks they can perform. These tasks come in the form of methods, and WriteLine is an example. A method is a named, reusable block of code that you can request to run. WriteLine’s task is to take text and display it in the console window on its own line. The act of asking a method to run is called method invocation or a method call. These method calls or invocations are performed by using a set of parentheses after the method name, which is why our one line of code contains WriteLine(...). Some methods require data to perform their task. WriteLine works that way. It needs to know what text to display. This data is supplied to the method call by placing it inside the parentheses, as we have seen with WriteLine("Hello, World!"). Some methods don’t need any extra information, while others need multiple pieces of information. We will see examples of those soon. Some methods can also return information when they finish, allowing data to flow to and from a method call. We’ll soon see examples of that as well. Namespaces All methods live in containers like a class, but even most classes live in other containers called namespaces. Namespaces are purely code organization tools, but they are valuable when dealing with hundreds or thousands of classes. The Console class lives in a namespace called System. If we add this to our code map, it looks like this: In code, we could have referred to Console through its namespace name. The following code is functionally identical to our earlier code: System.Console.WriteLine("Hello, World!"); Using C# 10 features and the project template we chose, we can skip the System. In older versions of C#, we would have somehow needed to account for System. One way to account 22 LEVEL 3 HELLO WORLD: YOUR FIRST PROGRAM for it was shown above. A second way is with a special line called a using directive. If you stumble into older C# code online or elsewhere, you may notice that most old C# code files start with a pile of lines that look like this: using System; These lines tell the compiler, “If you come across an identifier, look in this namespace for it.” It allows you to use a class name without sticking the namespace name in front of it. But with C# 10, the compiler will automatically search System and a handful of other extremely common namespaces without you needing to call it out. For the short term, we can almost ignore namespaces entirely. (We’ll cover them in more depth in Level 33.) But namespaces are an important element of the code structure, so even though it will be a while before we need to deal with namespaces directly, I’m still going to call out which namespaces things live in as we encounter them. (Most of it will be the System namespace.) The Base Class Library Our code map is far from complete. System, Console, and WriteLine are only a tiny slice of the entire collection of code called the Base Class Library (BCL). The Base Class Library contains many namespaces, each with many classes, each with many members. The code map below fleshes this out a bit more: It is huge! If we drew the complete diagram, it might be longer than this whole book! The Base Class Library provides every C# program with a set of fundamental building blocks. We won’t cover every single method or class in the Base Class Library, but we will cover its most essential parts throughout this book (starting with Console). Program and Main The code we write also adds new code elements. Even our simple Hello World program adds new code elements that we could show in a code map: SYNTAX AND STRUCTURE 23 The compiler takes the code we write, places it inside a method called Main, and then puts that inside a class called Program, even though we don’t see those names in our code. This is a slight simplification; the compiler uses a name you can’t refer to ($), but we’ll use the simpler name Main for now. In the code map above, the icon for Main also has a little black arrow to indicate that Main is the program’s entry point. The entry point or main method is the code that will automatically run when the computer runs your program. Other methods won’t run unless the main method calls them, as our Hello World program does with WriteLine. In the early days of C#, you had to write out code to define both Program and Main. You rarely need to do so now, but you can if you want (Level 33). Statements We have accounted for every character in our Hello World program except the semicolon (;) at the end. The entire Console.WriteLine("Hello, World!"); line is called a statement. A statement is a single step or command for the computer to run. Most C# statements end with a semicolon. This particular statement instructs the computer to ask the Console class to run its WriteLine method, giving it the text "Hello, World!" as extra information. This “ask a thing to do a thing” style of statement is common, but it is not the only kind. We will see others as we go. Statements don’t have names, so we won’t put them in a code map. Statements are an essential building block of C# programs. You instruct the computer to perform a sequence of statements one after the next. Most programs have many statements, which are executed from top to bottom and left to right (though C# programmers rarely put more than one statement on a single line). One thing that may surprise new programmers is how specific you need to be when giving the computer statements to run. Most humans can be given vague instructions and make judgment calls to fill in the gaps. Computers have no such capacity. They do exactly what they are told without variation. If it does something unexpected, it isn’t that the computer made a mistake. It means what you thought you commanded and what you actually commanded were not the same. As a new programmer, it is easy to think, “The computer isn’t doing what I told it!” Instead, try to train your mind to think, “Why did the computer do that instead of what I expected?” You will be a better programmer with that mindset. Whitespace C# ignores whitespace (spaces, tabs, newlines) as long as it can tell where one thing ends and the next begins. We could have written the above line like this, and the compiler wouldn’t care: Console. WriteLine ( "Hello, World!" ) ; But which is easier for you to read? This is a critical point about writing code: You will spend more time reading code than writing it. Do yourself a favor and go out of your way to make code easy to understand, regardless of what the compiler will tolerate. 24 LEVEL 3 HELLO WORLD: YOUR FIRST PROGRAM Challenge What Comes Next 50 XP The man seems surprised that you’ve produced a working “Hello, World!” program. “Been a while since I saw somebody program like that around here. Do you know what you’re doing with that? Can you make it do something besides just say ‘hello’?” Build on your original Hello World program with the following: Objectives: Change your program to say something besides “Hello, World!” BEYOND HELLO WORLD With an understanding of the basics behind us, let’s explore a few other essential features of C# and make a few more complex programs. Multiple Statements A C# program runs one statement at a time in the order they appear in the file. Putting multiple statements into your program makes it do multiple things. The following code displays three lines of text: Console.WriteLine("Hi there!"); Console.WriteLine("My name is Dug."); Console.WriteLine("I have just met you and I love you."); Each line asks the Console class to perform its WriteLine method with different data. Once all statements in the program have been completed, the program ends. Challenge The Makings of a Programmer 50 XP The man, who tells you his name is Ritlin, asks you to follow him over to a few of his friends, fishing on the dock. “This one here has the makings of a Programmer!” Ritlin says. The group looks at you with eyes widening and mouths agape. Ritlin turns back to you and continues, “I haven’t seen nor heard tell of anybody who can wield that power in a million clock cycles of the CPU. Nobody has been able to do that since the Uncoded One showed up in these lands.” He describes the shadowy and mysterious Uncoded One, an evil power that rots programs and perhaps even the world itself. The Uncoded One’s presence has prevented anybody from wielding the power of programming, the only thing that might be able to stop it. Yet somehow, you have been able to grab hold of this power anyway. Ritlin’s companions suddenly seem doubtful. “Can you show them what you showed me? Use some of that Programming of yours to make a program? Maybe something with more than one statement in it?” Objectives: Make a program with 5 Console.WriteLine statements in it. Answer this question: How many statements do you think a program can contain? Expressions Our next building block is an expression. Expressions are bits of code that your program must process or evaluate to determine their value. We use the same word in the math world to refer BEYOND HELLO WORLD 25 to something like 3 + 4 or -2 × 4.5. Expressions describe how to produce a value from smaller elements. The computer can use an expression to compute a value as it runs. C# programs use expressions heavily. Anywhere a value is needed, an expression can be put in its place. While we could do this: Console.WriteLine("Hi User"); We can also use an expression instead: Console.WriteLine("Hi " + "User"); The code "Hi " + "User" is an expression rather than a single value. As your program runs, it will evaluate the expression to determine its value. This code shows that you can use + between two bits of text to produce the combined text ("Hi User"). The + symbol is one of many tools that can be used to build expressions. We will learn more as we go. Expressions are powerful because they can be assembled out of other, smaller expressions. You can think of a single value like "Hi User" as the simplest type of expression. But if we wanted, we could split "User" into "Us" + "er" or even into "U" + "s" + "e" + "r". That isn’t very practical, but it does illustrate how you can build expressions out of smaller expressions. Simpler expressions are better than complicated ones that do the same job, but you have lots of flexibility when you need it. Every expression, once evaluated, will result in a single new value. That single value can be used in other expressions or other parts of your code. Variables Variables are containers for data. They are called variables because their contents can change or vary as the program runs. Variables allow us to store data for later use. Before using a variable, we must indicate that we need one. This is called declaring the variable. In doing so, we must provide a name for the variable and indicate its type. Once a variable exists, we can place data in the variable to use later. Doing so is called assignment, or assigning a value to the variable. Once we have done that, we can use the variable in expressions later. All of this is shown below: string name; name = "User"; Console.WriteLine("Hi " + name); The first line declares the variable with a type and a name. Its type is string (the fancy programmer word for text), and its name is name. This line ensures we have a place to store text that we can refer to with the identifier name. The second line assigns it a value of "User". We use the variable in an expression on the final line. As your program runs, it will evaluate the expression "Hi " + name by retrieving the current value in the name variable, then combining it with the value of "Hi ". We’ll see plenty more examples of expressions and variables soon. Anything with a name can be visualized on a code map, and this name variable is no exception. The following code map shows this variable inside of Main, using a box icon: 26 LEVEL 3 HELLO WORLD: YOUR FIRST PROGRAM In Level 9, we’ll see why it can be helpful to visualize where variables fit on the code map. You may notice that when you type string in your editor, it changes to a different color (usually blue). That is because string is a keyword. A keyword is a word with special meaning in a programming language. C# has over 100 keywords! We’ll discuss them all as we go. Reading Text from the Console Some methods produce a result as a part of the job they were designed to do. This result can be stored in a variable or used in an expression. For example, Console has a ReadLine method that retrieves text that a person types until they hit the Enter key. It is used like so: Console.ReadLine() ReadLine does not require any information to do its job, so the parentheses are empty. But the text it sends back can be stored in a variable or used in an expression: string name; Console.WriteLine("What is your name?"); name = Console.ReadLine(); Console.WriteLine("Hi " + name); This code no longer displays the same text every time. It waits for the user to type in their name and then greets them by name. When a method produces a value, programmers say it returns the value. So you might say that Console.ReadLine() returns the text the user typed. Challenge Consolas and Telim 50 XP These lands have not seen Programming in a long time due to the blight of the Uncoded One. Even old programs are now crumbling to bits. Your skills with Programming are only fledgling now, but you can still make a difference in these people’s lives. Maybe someday soon, your skills will have grown strong enough to take on the Uncoded One directly. But for now, you decide to do what you can to help. In the nearby city of Consolas, food is running short. Telim has a magic oven that can produce bread from thi

Use Quizgecko on...
Browser
Browser