Head First C#, 5th Edition

Book description

What will you learn from this book?

Create apps, games, and more using this engaging, highly visual introduction to C#, .NET, and Visual Studio. In the first chapter you'll dive right in, building a fully functional game using C# and .NET MAUI that can run on Windows, Mac, and even Android and iOS devices. You'll learn how to use classes and object-oriented programming, create 3D games in Unity, and query data with LINQ. And you'll do it all by solving puzzles, doing hands-on exercises, and building real-world applications. Interested in a development career? You'll learn important development techniques and ideas—many who learned to code with this book are now professional developers, team leads, coding streamers, and more. There's no experience required except the desire to learn. And this is the best place to start.

What's so special about this book?

If you've read a Head First book, you know what to expect: a visually rich format designed for the way your brain works. If you haven't, you're in for a treat. With this book, you'll learn C# through a multisensory experience that engages your mind—rather than a text-heavy approach that puts you to sleep.

Publisher resources

View/Submit Errata

Table of contents

  1. Related books from O’Reilly
    1. Other books in O’Reilly’s Head First series
  2. Table of Contents (the real thing)
  3.  
  4. How to use this Book Intro
    1. Who is this book for?
      1. Who should probably back away from this book?
    2. We know what you’re thinking
    3. We know what your brain is thinking
    4. Metacognition: thinking about thinking
    5. Here’s what WE did:
    6. Here’s what YOU can do to bend your brain into submission
    7. README.md
    8. The technical review team
    9. “Shoulders of giants”
    10. Acknowledgments
      1. ...and a few more folks who have been so incredibly supportive over the years
  5. 1. Start Building Apps with C# Build something great...fast!
    1. Learn C#...and learn to become a great developer
      1. ...with a learning system that’s effective and fun
    2. Write code and explore C# with Visual Studio
      1. Visual Studio is your free gateway to C#
    3. Install Visual Studio Community Edition
    4. Run Visual Studio
    5. Create and run your first C# project in Visual Studio
    6. You can use Visual Studio Code with Head First C#
    7. Install the C# extensions
      1. Change the C# debug console setting
    8. Create and run your first project in Visual Studio Code
    9. Set up Visual Studio Code for the next project
      1. First open a folder, then add a project
      2. The Command Palette
      3. Install .NET MAUI before reading the rest of this chapter
      4. If you’re using Linux, you’ll need an Android device for the .NET MAUI projects
    10. Let’s build a game!
    11. Break up large projects into smaller parts
    12. Here’s how you’ll build your game
    13. Create a .NET MAUI project in Visual Studio
    14. Create a .NET MAUI project in Visual Studio Code
    15. Run your new .NET MAUI app
      1. Stop your MAUI app
    16. MAUI apps work on all of your devices
    17. Here’s the page that you’ll build
    18. Start editing your XAML code
    19. Add the XAML for a Button and a Label
    20. Use a FlexLayout to make a grid of animal buttons
    21. Write C# code to add the animals to the buttons
    22. Start editing the PlayAgainButton event handler method
      1. Add a C# statement to the event handler method
    23. Add more statements to your event handler
    24. Add animals to your buttons
    25. Run your app!
      1. Here are just a few things Git can do for you
    26. Visual Studio makes it easy to use Git
    27. Add C# code to handle mouse clicks
    28. Enter the code for the event handler
    29. Run your app and find all the pairs
      1. Uh-oh—there’s a bug in your code
      2. When you find a bug, you need to sleuth it out
    30. Finish the game by adding a timer
    31. Add a timer to your game’s code
    32. Finish the code for your game
      1. Add a field to hold the time elapsed
      2. Finish your TimerTick method
    33. Even better ifs...
  6. 2. Variables, Statements, and Methods Dive into C# code
    1. Take a closer look at the files in your console app
      1. A statement performs one single action
    2. Statements are the building blocks for your apps
    3. Statements live inside methods
      1. Methods do something
      2. Methods help you organize your code
    4. Your methods use variables to work with data
      1. Declare your variables
      2. Variables vary
      3. You need to assign values to variables before you use them
      4. A few useful types
    5. Generate a new method to work with variables
    6. Add code that uses operators to your method
    7. Use the debugger to watch your variables change
    8. Use code snippets to help write loops
    9. Use operators to work with variables
    10. if statements make decisions
      1. if/else statements also do something if a condition isn’t true
    11. Loops perform an action over and over
      1. while loops keep looping statements while a condition is true
      2. do/while loops run the statements then check the condition
      3. for loops run a statement after each loop
    12. Some useful things to keep in mind about C# code
    13. Controls drive the mechanics of your user interfaces
      1. Meet some of the controls you’ll use in this book
    14. Other controls you’ll use in this book
    15. Build a .NET MAUI app to experiment with controls
    16. Create a new app to experiment with controls
    17. Explore your new MAUI app and figure out how it works
    18. Add an Entry control to your app
    19. Add properties to your Entry control
    20. Make your Entry control update a Label control
    21. Combine horizontal and vertical stack layouts
      1. You’ll nest one Layout inside another
    22. Add a Picker control to display a list of choices
  7. Unity Lab #1 Explore C# with Unity
    1. Unity is a powerful tool for game design
    2. Download Unity Hub
    3. Use Unity Hub to create a new project
      1. Work with your project in the Unity editor
    4. Take control of the Unity layout
      1. Choose the Wide layout to match our screenshots
      2. Set up Unity to work with Visual Studio
    5. Your scene is a 3D environment
    6. Unity games are made with GameObjects
    7. Use the Move Gizmo to move your GameObjects
    8. The Inspector shows your GameObject’s components
    9. Add a material to your Sphere GameObject
    10. Rotate your sphere
      1. Move the Scene view camera with the View Tool and Scene Gizmo
      2. Get creative!
  8. 3. Namespaces and Classes Organizing your code
    1. Classes help you organize your code
    2. If code is useful, classes can help you reuse it
    3. Some methods take parameters and return a value
    4. Visual Studio helps you explore parameters and return values
    5. Let’s build an app that picks random cards
    6. You’ll use an array to store the cards
    7. Create an app with a Main method
      1. Create your PickRandomCards app without top-level statements
    8. Add a class called CardPicker to your app
    9. Use Quick Actions to remove unnecessary using lines
    10. Convert between namespace styles
    11. Use the new keyword to create an array of strings
      1. Here’s the code for your finished CardPicker class
    12. Ana’s working on her next game
    13. Ana’s game is evolving...
      1. ...so how can Ana make things easier for herself?
    14. Build a paper prototype for a classic game
    15. Build a MAUI version of your random card app
      1. Make your app accessible!
    16. Make your MAUI app pick random cards
    17. Reuse your CardPicker class
    18. Add a using directive to use code in another namespace
    19. Ana’s prototypes look great...
      1. ...but what if she wants more than one enemy?
    20. Ana can use objects to solve her problem
    21. You use a class to build an object
      1. An object gets its methods from its class
    22. When you create a new object from a class, it’s called an instance of that class
    23. A better solution for Ana...brought to you by objects
      1. Theory and practice
    24. An instance uses fields to keep track of things
      1. Methods are what an object does. Fields are what an object knows.
    25. Thanks for the memory
    26. What’s on your app’s mind
    27. Sometimes code can be difficult to read
      1. Extremely compact code can be especially problematic
    28. Most code doesn’t come with a manual
    29. Use intuitive class and method names
    30. Build a class to work with some guys
    31. There’s an easier way to initialize objects with C#
    32. Use the C# Interactive window or csi to run C# code
  9. 4. Data, Types, Objects, and References Managing your app’s data
    1. Owen could use our help!
      1. Storytelling, fantasy, and mechanics
    2. Character sheets store different types of data on paper
    3. A variable’s type determines what kind of data it can store
    4. C# has several types for storing integers
    5. Types for storing really HUGE and really tiny numbers
    6. Let’s talk about strings
    7. A literal is a value written directly into your code
      1. Use suffixes to give your literals types
    8. A variable is like a data to-go cup
      1. Use the Convert class to explore bits and bytes
    9. Other types come in different sizes too
    10. 10 pounds of data in a 5-pound bag
    11. Casting lets you copy values that C# can’t automatically convert to another type
      1. So what happened?
      2. When you cast a value that’s too big, C# adjusts it to fit its new container
    12. C# does some conversions automatically
    13. When you call a method, the arguments need to be compatible with the types of the parameters
    14. Owen is constantly improving his game...
      1. ...but the trial and error can be time-consuming
    15. Let’s help Owen experiment with ability scores
    16. Fix the compiler error by adding a cast
      1. Add a cast to get the AbilityScoreCalculator class to compile...
      2. ...but there’s still a bug!
      3. Now we can finally fix Owen’s bug—and get the REAL Sharpen answer
    17. Use reference variables to access your objects
    18. References are like sticky notes for your objects
    19. If there aren’t any more references, your object gets garbage-collected
    20. Multiple references and their side effects
    21. Two references mean TWO variables that can change the same object’s data
    22. Objects use references to talk to each other
    23. Arrays hold multiple values
      1. Use each element in an array like it’s a normal variable
    24. Arrays can contain reference variables
    25. null means a reference points to nothing
      1. Console.ReadLine returns a null when there are no lines available
    26. Use the string? type when a string might be null
      1. int.TryParse takes a string? parameter
    27. Welcome to Sloppy Joe’s Budget House o’ Discount Sandwiches!
    28. Sloppy Joe’s menu app uses a Grid layout
    29. Grid controls
      1. Use Grid properties to put a control in a cell
    30. Define the rows and columns for a Grid
    31. Create the Sloppy Joe’s menu app and set up the grid
      1. Here’s the XAML for the app
    32. The C# code for the main page
    33. Can we make the app more accessible?
      1. Set the main header so the screen reader narrates it
      2. Try setting the item1 label’s SemanticProperties.Description instead
    34. Use the SetValue method to change a control’s semantic properties
  10. Unity Lab #2 Write C# Code for Unity
    1. C# scripts add behavior to your GameObjects
    2. Add a C# script to your GameObject
    3. Write C# code to rotate your sphere
    4. Add a breakpoint and debug your game
      1. Use a hit count to skip frames
    5. Use the debugger to understand Time.deltaTime
    6. Add a cylinder to show where the Y axis is
    7. Add fields to your class for the rotation angle and speed
    8. Use Debug.DrawRay to explore how 3D vectors work
      1. Use Unity to visualize vectors in 3D
    9. Run the game to see the ray in the Scene view
      1. Add a duration to the ray so it leaves a trail
    10. Rotate your ball around a point in the scene
    11. Use Unity to take a closer look at rotation and vectors
    12. Get creative!
  11. 5. Encapsulation How objects keep their Secrets
    1. Let’s help Owen roll for damage
    2. Create a console app to calculate damage
    3. Design a MAUI version of the damage calculator app
      1. How your damage calculator app will work
    4. Tabletop talk (or maybe...dice discussion?)
    5. Let’s try to fix that bug
      1. Oops! It’s still not working
    6. Use Debug.WriteLine to print diagnostic information
    7. It’s easy to accidentally misuse your objects
    8. Encapsulation means keeping some data in a class private
      1. When in doubt, make it private
    9. Use encapsulation to control access to your class’s methods and fields
    10. But is the RealName field REALLY protected?
    11. Private fields and methods can only be accessed from instances of the same class
    12. Why encapsulation? Think of an object as an opaque box...
      1. Encapsulation makes your classes...
    13. Let’s use encapsulation to improve the SwordDamage class
      1. Is every member of the SwordDamage class public?
      2. Are fields or methods being misused?
      3. Is there calculation required after setting a field?
      4. So what fields and methods really need to be public?
    14. Encapsulation keeps your data safe
      1. Let’s use encapsulation in a class
    15. Write a console app to test the PaintballGun class
      1. Our class is well-encapsulated, but...
    16. Properties make encapsulation easier
      1. Replace the GetBalls and SetBalls methods with a property
    17. Modify your top-level statements to use the Balls property
      1. Debug your PaintballGun class to understand how the property works
    18. Auto-implemented properties simplify your code
      1. Use the prop snippet to create an auto-implemented property
    19. Use a private setter to create a read-only property
      1. Make the BallsLoaded setter private
    20. What if we want to change the magazine size?
      1. But there’s a problem...how do we initialize MagazineSize?
    21. Use a constructor with parameters to initialize properties
    22. Specify arguments when you use the new keyword
    23. Initialize fields and properties inline or in the constructor
    24. Make the screen reader announce each roll
    25. A few useful facts about methods and properties
  12. 6. Inheritance Your Object’s Family Tree
    1. Calculate damage for MORE weapons
    2. Use a switch statement to match several candidates
    3. One more thing...can we calculate damage for a dagger? And a mace? And a staff? and...
    4. When your classes use inheritance, you only need to write your code once
    5. Build up your class model by starting general and getting more specific
    6. How would you design a zoo simulator?
    7. Different animals have different behaviors
    8. Every subclass extends its base class
      1. C# always calls the most specific method
    9. Any place where you can use a base class, you can use one of its subclasses instead
    10. Use a colon to extend a base class
    11. We know that inheritance adds the base class fields, properties, and methods to the subclass...
      1. ...but some birds don’t fly!
    12. A subclass can override methods to change or replace members it inherited
    13. Some members are only implemented in a subclass
    14. Use the debugger to understand how overriding works
    15. Build an app to explore virtual and override
    16. A subclass can hide methods in the base class
      1. Hiding methods vs. overriding methods
      2. Use the new keyword when you’re hiding methods
      3. Use different references to call hidden methods
    17. Use the override and virtual keywords to inherit behavior
    18. A subclass can access its base class using the base keyword
    19. When a base class has a constructor, your subclass needs to call it
    20. A subclass and base class can have different constructors
    21. It’s time to finish the job for Owen
      1. Use the debugger to really understand how these classes work
    22. A class should do one thing
    23. Build a beehive management system
    24. How the Beehive Management System app works
    25. The page uses a grid to lay out the controls for the UI
      1. The Bee Jobs box uses a Border with a VerticalStackLayout
    26. The Beehive Management System class model
    27. All bees in the system extend the Bee class
    28. All the constants are in their own static class
    29. The worker bees extend the Bee class
    30. The Queen class: how she manages the worker bees
    31. Here’s the code-behind for MainPage.xaml.cs
    32. Feedback drives your beehive management game
      1. Workers and honey are in a feedback loop
    33. The Beehive Management System is turn-based... now let’s convert it to real-time
    34. Some classes should never be instantiated
    35. An abstract class is an intentionally incomplete class
      1. Let’s plan a trip to another planet
    36. Like we said, some classes should never be instantiated
      1. Solution: use an abstract class
    37. An abstract method doesn’t have a body
    38. Abstract properties work just like abstract methods
    39. The Deadly Diamond of Death
  13. Unity Lab #3 GameObject Instances
    1. Let’s build a game in Unity!
    2. Create a new material inside the Materials folder
    3. Spawn a billiard ball at a random point in the scene
    4. Use the debugger to understand Random.value
    5. Turn your GameObject into a prefab
    6. Create a script to control the game
    7. Attach the GameController script to the Main Camera
    8. Press Play to run your code
      1. Watch the live instances in the Hierarchy window
    9. Use the Inspector to work with GameObject instances
    10. Use physics to keep balls from overlapping
    11. Get creative!
  14. 7. Interfaces, Casting, and “is” Making classes keep their Promises
    1. The beehive is under attack!
      1. HiveDefender needs a DefendHive method because enemies can attack at any time
    2. We could use casting to call the DefendHive method…
      1. …but what if we add more Bee subclasses that can defend?
    3. An interface defines methods and properties that a class must implement…
      1. …but there’s no limit to the number of interfaces a class can implement
    4. Interfaces let unrelated classes do the same job
    5. Get a little practice using interfaces
    6. Fireside Chats
    7. You can’t instantiate an interface, but you can reference an interface
      1. If you try to instantiate an interface, your code won’t build
      2. Use the interface to reference an object you already have
    8. Pool Puzzle
    9. Pool Puzzle Solution
    10. Interface references are ordinary object references
    11. The RoboBee 4000 can do a worker bee’s job without using valuable honey
    12. The IWorker’s Job property is a hack
    13. Use is to check the type of an object
    14. Use is to access methods in a subclass
    15. What if we want different animals to swim or hunt in packs?
    16. Use interfaces to work with classes that do the same job
      1. Use the “is” keyword to check if the Animal is a swimmer or pack hunter
    17. Safely navigate your class hierarchy with is
    18. C# has another tool for safe type conversion: the as keyword
    19. Use upcasting and downcasting to move up and down a class hierarchy
    20. A quick example of upcasting
    21. Upcasting turns your CoffeeMaker into an Appliance
    22. Downcasting turns your Appliance back into a CoffeeMaker
    23. Upcasting and downcasting work with interfaces too
    24. Interfaces can inherit from other interfaces
    25. Interfaces can have static members
    26. Default implementations give bodies to interface methods
    27. Add a ScareAdults method with a default implementation
    28. Data binding updates MAUI controls automatically
    29. Add data binding to the default MAUI app
    30. Make Moods implement the INotifyPropertyChanged interface
    31. Use the PropertyChanged event to make data binding work
    32. Polymorphism means that one object can take many different forms
      1. Keep your eyes open for polymorphism!
      2. The four core principles of object-oriented programming
  15. 8. Enums and Collections Organizing your data
    1. If a constructor just sets fields, use a primary constructor instead
    2. A primary constructor can extend a base constructor
      1. Overloaded constructors use this to call the primary constructor
    3. Strings don’t always work for storing categories of data
    4. Enums let you work with a set of valid values
      1. An enum defines a new type
    5. Enums let you represent numbers with names
    6. We could use an array to create a deck of cards…
      1. …but what if you wanted to do more?
    7. Arrays can be annoying to work with
    8. Lists make it easy to store collections of…anything
    9. Lists are more flexible than arrays
    10. Let’s build an app to store shoes
    11. Generic collections can store any type
      1. Generic lists are declared using <angle brackets>
    12. You can use collection expressions to create Lists
    13. Let’s create a List of Ducks
      1. Use a collection expression to create a List of Ducks
    14. Sorting lists can be tricky
      1. Lists know how to sort themselves
    15. IComparable<Duck> helps your List sort its Ducks
      1. An object’s CompareTo method compares it to another object
    16. Use IComparer to tell your List how to sort
      1. Add an IComparer to your project
    17. Create an instance of your comparer object
      1. Multiple IComparer implementations, multiple ways to sort your objects
    18. Comparers can do complex comparisons
    19. Overriding a ToString method lets an object describe itself
      1. Override the ToString method to see your Ducks in the IDE
    20. Update your foreach loops to let your Ducks and Cards write themselves to the console
      1. Add a ToString method to your Card object too
    21. You can upcast an entire list using IEnumerable<T>
    22. Use a Dictionary to store keys and values
      1. How to use a Dictionary
    23. The Dictionary functionality rundown
      1. Your key and value can be different types
    24. Write an app that uses a Dictionary
      1. Use a collection initializer to create the Dictionary
    25. And yet MORE collection types…
      1. Generic .NET collections implement IEnumerable
    26. A queue is FIFO—first in, first out
    27. A stack is LIFO—last in, first out
    28. CollectionView is a MAUI control built for displaying collections
    29. ObservableCollection is a collection made for data binding
    30. Add your Card class to the project
    31. Use XAML to instantiate your objects for data binding
    32. Modify your app to use a resource Dictionary
    33. Modify the event handlers to use the resource Dictionary
    34. Use what you’ve learned to build an app with two decks
  16. Unity Lab #4 User Interfaces
    1. Add a score that goes up when the player clicks a ball
    2. Add two different modes to your game
    3. Add game mode to your game
    4. Add a UI to your game
      1. Use the 2D view to work with the Canvas
    5. Set up the Text that will display the score in the UI
    6. Add a Button that calls a method to start the game
    7. Make the Play Again button and Score Text work
    8. Finish the code for the game
    9. Get creative!
  17. 9. LINQ and Lambdas Get Control of your data
    1. Jimmy’s a Captain Amazing superfan...
    2. ...but his collection’s all over the place
    3. Use LINQ to query your collections
    4. LINQ works with any sequence
      1. LINQ methods enumerate your sequences—just like foreach loops
    5. LINQ’s query syntax
      1. LINQ queries are built from clauses
    6. LINQ works with objects
    7. Use a LINQ query to finish the app for Jimmy
    8. The var keyword lets C# figure out variable types for you
      1. When you use var, C# figures out the variable’s type automatically
    9. LINQ is versatile
    10. LINQ queries aren’t run until you access their results
    11. Use a group query to separate your sequence into groups
    12. Use join queries to merge data from two sequences
    13. Use the new keyword to create anonymous types
    14. Unit tests help you make sure your code works
      1. Add a second project to your solution for the unit tests
    15. Start writing your first test method
      1. Run the unit test
    16. Give your unit tests access to the classes they’re testing
      1. Add a project reference so the unit tests can access the classes they need to test
    17. One project can only access public classes in another project
      1. Make your JimmyLinq classes and enums public
    18. Use the Arrange-Act-Assert pattern to write an effective test
      1. Use Assert.AreEqual to check that a calculated value matches an expected value
    19. Finish your first unit test
    20. Write a unit test for the GetReviews method
    21. Write unit tests to handle edge cases and weird data
    22. Use the => operator to create lambda expressions
    23. Refactor a clown with lambdas
    24. Use the ?: operator to make your lambdas make choices
    25. LINQ queries are made up of methods
      1. You can use lambda expressions with methods that take a Func parameter
    26. LINQ declarative syntax can be refactored into chained methods
    27. Use the => operator to create switch expressions
    28. Explore the Enumerable class
      1. Enumerable.Empty creates an empty sequence of any type
      2. Enumerable.Repeat repeats a value a specific number of times
      3. So what exactly is an IEnumerable<T>?
    29. Create an enumerable sequence by hand
    30. Use yield return to create your own sequences
      1. Use the debugger to explore yield return
    31. Use yield return to refactor ManualSportSequence
      1. Add an indexer to BetterSportSequence
    32. Collectioncross
    33. Collectioncross solution
  18. 10. Reading and Writing Files Save the last byte for me
    1. .NET uses streams to read and write data
    2. Different streams read and write different things
      1. Things you can do with a stream:
    3. A FileStream reads and writes bytes in a file
    4. Write text to a file in three simple steps
    5. The Swindler launches another diabolical plan
      1. StreamWriter.WriteLine works just like Console.WriteLine
    6. StreamWriter Magnets
    7. StreamWriter Magnets Solution
    8. Use a StreamReader to read a file
    9. Data can go through more than one stream
    10. Use the static File and Directory classes to work with files and directories
      1. Things you can do with the static File class:
      2. Things you can do with the static Directory class:
    11. IDisposable makes sure objects are closed properly
      1. Use the IDE to explore IDisposable
    12. Avoid filesystem errors with using statements
      1. Use multiple using statements for multiple objects
    13. Use a MemoryStream to stream data to memory
      1. Use Encoding.UTF8.GetString to convert byte arrays to strings
    14. What happens to an object when it’s serialized?
    15. But what exactly IS an object’s state? What needs to be saved?
    16. When an object is serialized, all of the objects it refers to get serialized too…
    17. Use JsonSerializer to serialize your objects
    18. JSON only includes data, not specific C# types
    19. Next up: we’ll take a deep dive into our data
    20. C# strings are encoded with Unicode
    21. Visual Studio works really well with Unicode
    22. .NET uses Unicode to store characters and text
    23. C# can use byte arrays to move data around
    24. Use a BinaryWriter to write binary data
    25. Use BinaryReader to read the data back in
    26. A hex dump lets you see the bytes in your files
      1. How to make a hex dump of some plain text
    27. Use StreamReader to build a hex dumper
    28. Use Stream.Read to read bytes from a stream
    29. Modify your hex dumper to read directly from the stream
    30. Run your app from the command line
      1. Use the args variable to access command-line arguments
    31. Pass command-line arguments to an app run in the IDE
  19. Unity Lab #5 Raycasting
    1. Create a new Unity project and start to set up the scene
    2. Set up the camera
    3. Create a GameObject for the player
    4. Introducing Unity’s navigation system
    5. Install the AI Navigation package
    6. Things you’ll do with navigation
    7. Set up the NavMesh
      1. Fix the carved-out hole in your NavMesh
    8. Make your player automatically navigate the play area
  20. 11. Captain Amazing the Death of the Object
    1. The life and death of an object
    2. Use the GC class (with caution) to force garbage collection
    3. Your last chance to DO something... your object’s finalizer
    4. When EXACTLY does a finalizer run?
      1. You can SUGGEST to .NET that it’s time to collect the garbage
    5. Finalizers can’t depend on other objects
      1. Don’t use finalizers for serialization
    6. A struct looks like an object...
      1. ...but isn’t an object
    7. Values get copied; references get assigned
    8. Structs are value types; objects are reference types
      1. Here’s what happened...
    9. The stack vs. the heap: more on memory
    10. Use out parameters to make a method return more than one value
    11. Pass by reference using the ref modifier
    12. Use optional parameters to set default values
    13. A null reference doesn’t refer to any object
    14. Non-nullable reference types help you avoid NREs
      1. Use encapsulation to prevent your property from ever being null
    15. Nullable value types can be null...and handled safely
    16. The null-coalescing operator ?? checks for nulls automatically
      1. ?? checks for null and returns an alternative
      2. ??= assigns a value to a variable only if it’s null
    17. “Captain” Amazing...not so much
    18. Records give your objects value equality automatically
    19. Don’t modify records—copy them
      1. Use the with keyword to create a modified copy of your Duck
    20. Extension methods add new behavior to EXISTING classes
    21. Extending a fundamental type: string
  21. 12. Exception Handling Putting out fires gets old
    1. Your hex dumper reads a filename from the command line
      1. But what happens if you give HexDump an invalid filename?
    2. When your program throws an exception, the CLR generates an Exception object
    3. All Exception objects inherit from System.Exception
    4. There are some files you just can’t dump
    5. What happens when a method you want to call is risky?
    6. Handle exceptions with try and catch
    7. Use the debugger to follow the try/catch flow
    8. If you have code that ALWAYS needs to run, use a finally block
    9. Catch-all exceptions handle System.Exception
      1. Avoid catch-all exception with multiple catch blocks
    10. Pool Puzzle
    11. Pool Puzzle Solution
    12. Use the right exception for the situation
      1. Catch custom exceptions that extend System.Exception
    13. Exception Magnets
    14. Exception Magnets Solution
    15. Exception filters help you create precise handlers
    16. The worst catch block EVER: catch-all plus comments
      1. You should handle your exceptions, not bury them
    17. Temporary solutions are OK (temporarily)
    18. Use NuGet to add a logging library to your app
      1. Packages add DLLs with classes
    19. Add logging to your ExceptionExperiment app
  22. Unity Lab #6 Scene Navigation
    1. Let’s pick up where the last Unity Lab left off
    2. Add a platform to your scene
    3. Use bake options to make the platform walkable
    4. Include the stairs and ramp in the NavMesh
    5. Make the player navigate around the obstacles
      1. Fix the moving obstacle
    6. Get creative!
    7. Thank you for reading our book!
      1. But wait, there’s more! Your journey’s just begun...
      2. Check out these essential (and amazing!) books written by our friends and colleagues, also published by
  23. Index
  24. The Authors

Product information

  • Title: Head First C#, 5th Edition
  • Author(s): Andrew Stellman, Jennifer Greene
  • Release date: July 2024
  • Publisher(s): O'Reilly Media, Inc.
  • ISBN: 9781098141783