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. 1. Start Building apps with C#: Build Something Great…Fast!
    1. Why you should learn C#
    2. Write code and explore C# with Visual Studio
      1. Visual Studio is your gateway to C#
    3. Install Visual Studio Community Edition
    4. Run Visual Studio
    5. Create your first project in Visual Studio – Windows edition
    6. Create your first project in Visual Studio – Mac edition
    7. Let’s build a game!
    8. Break up large projects into smaller parts
    9. Here’s how you’ll build your game
    10. Create a .NET MAUI project in Visual Studio – Windows edition
    11. Create a .NET MAUI project in Visual Studio – Mac edition
    12. Run your new .NET MAUI app
      1. Stop your MAUI app
    13. MAUI apps work on all of your devices
    14. Here’s the page that you’ll build
    15. Start editing your XAML code
    16. Add the XAML for a Button and a Label
    17. Use a FlexLayout to make a grid of animal buttons
    18. Write C# code to add the animals to the buttons
    19. Start editing the PlayAgainButton event handler method
      1. Add a C# statement to the event handler method
    20. Add more statements to your event handler
    21. Add animals to your buttons
    22. Run your app!
      1. Here are just a few things Git can do for you
    23. Visual Studio makes it easy to use Git
    24. Add C# code to handle mouse clicks
    25. Enter the code for the event handler
    26. 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
    27. Finish the game by adding a timer
    28. Add a timer to your game’s code
    29. Finish the code for your game
      1. Add a field to hold the time elapsed
      2. Finish your TimerTick method
    30. Even better ifs…
  2. 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 of 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 operators to work with variables
    9. “if” statements make decisions
      1. if/else statements also do something if a condition isn’t true
    10. 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
    11. Use code snippets to help write loops
    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
    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
  3. 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
    8. Create your PickRandomCards app without top-level statements
    9. Add a class called CardPicker to your app
    10. Use Quick Actions to remove unnecessary ‘using’ lines
    11. Convert between namespace styles
    12. Use the new keyword to create an array of strings
    13. Here’s the code for your finished CardPicker class
    14. Ana’s working on her next game
    15. Ana’s game is evolving…
    16. …so how can Ana make things easier for herself?
    17. Build a paper prototype for a classic game
    18. Build a MAUI version of your random card app
    19. Make your app accessible!
    20. Make your MAUI app pick random cards
    21. Reuse your the CardPicker class
    22. Add a using directive to use code in another namespace
    23. Ana’s prototypes look great…
      1. …but what if she wants more than one enemy?
    24. Ana can use objects to solve her problem
    25. You use a class to build an object
      1. An object gets its methods from its class
    26. When you create a new object from a class, it’s called an instance of that class
    27. A better solution for Ana…brought to you by objects
      1. Theory and practice
    28. An instance uses fields to keep track of things
      1. Methods are what an object does. Fields are what the object knows.
    29. Thanks for the memory
    30. What’s on your app’s mind
    31. Sometimes code can be difficult to read
      1. Extremely compact code can be especially problematic
    32. Most code doesn’t come with a manual
    33. Use intuitive class and method names
    34. Build a class to work with some guys
    35. There’s an easier way to initialize objects with C#
    36. Use the C# Interactive window or csi to run C# code
  4. 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...
    15. ...but the trial and error can be time-consuming
    16. Let’s help Owen experiment with ability scores
    17. 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
    18. Use reference variables to access your objects
    19. References are like sticky notes for your objects
    20. If there aren’t any more references, your object gets garbage-collected
    21. Multiple references and their side effects
    22. Two references mean TWO variables that can change the same object’s data
    23. Objects use references to talk to each other
    24. Arrays hold multiple values
      1. Use each element in an array like it’s a normal variable
    25. Arrays can contain reference variables
    26. null means a reference points to nothing
      1. Console.ReadLine returns a null when there are no lines available
    27. Use the string? type when a string might be null
      1. int.TryParse takes a string? parameter
    28. Welcome to Sloppy Joe’s Budget House o’ Discount Sandwiches!
    29. Sloppy Joe’s menu app uses a Grid layout
    30. Grid controls
      1. Use Grid properties to put a control in a cell
    31. Define the rows and columns for a Grid
    32. Create the Sloppy Joe’s menu app and set up the grid
      1. Here’s the XAML for the app.
    33. The C# code for the main page
    34. 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
    35. Use the SetValue method to change a control’s semantic properties
  5. 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. A few ideas for encapsulating classes
    14. 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?
    15. Encapsulation keeps your data safe
      1. Let’s use encapsulation in a class
    16. Write a console app to test the PaintballGun class
      1. Our class is well-encapsulated, but...
    17. Properties make encapsulation easier
      1. Replace the GetBalls and SetBalls methods with a property
    18. Modify your top-level statements to use the Balls property
      1. Debug your PaintballGun class to understand how the property works
    19. Auto-implemented properties simplify your code
      1. Use the prop snippet to create an auto-implemented property
    20. Use a private setter to create a read-only property
      1. Make the BallsLoaded setter private
    21. What if we want to change the magazine size?
      1. But there’s a problem...how do we initialize MagazineSize?
    22. Use a constructor with parameters to initialize properties
    23. Specify arguments when you use the “new” keyword
    24. Pool Puzzle
    25. Pool Puzzle Solution
    26. Initialize fields and properties inline or in the constructor
    27. Make the screen reader announce each roll
    28. A few useful facts about methods and properties
    29. Objectcross
  6. 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. Thank you for returning my precious jewels!
      2. Hiding methods versus overriding methods
      3. Use the new keyword when you’re hiding methods
      4. 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 do should just 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
  7. 7. Interfaces, Casting, and “is”: Making Classes keep their Promises
    1. The beehive is under attack!
    2. HiveDefender needs a DefendHive method because enemies can attack at any time
    3. We could use casting to call the DefendHive method…
      1. …but what if we add more Bee subclasses that can defend?
    4. 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
    5. Interfaces let unrelated classes do the same job
    6. Get a little practice using interfaces
      1. What’s the picture ?
    7. What’s the declaration ?
    8. 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
    9. Interface references are ordinary object references
    10. The RoboBee 4000 can do a worker bee’s job without using valuable honey
    11. The IWorker’s Job property is a hack
    12. Use “is” to check the type of an object
    13. Use “is” to access methods in a subclass
    14. What if we want different animals to swim or hunt in packs?
    15. 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
    16. Safely navigate your class hierarchy with “is”
    17. C# has another tool for safe type conversion: the “as” keyword
    18. Use upcasting and downcasting to move up and down a class hierarchy
    19. A quick example of upcasting
    20. Upcasting turns your CoffeeMaker into an Appliance
    21. Downcasting turns your Appliance back into a CoffeeMaker
    22. Upcasting and downcasting work with interfaces, too
    23. Interfaces can inherit from other interfaces
    24. Interfaces can have static members
    25. Default implementations give bodies to interface methods
    26. Add a ScareAdults method with a default implementation
    27. Data binding updates MAUI controls automatically
    28. Add data binding to the default MAUI app
    29. Make Moods implement the INotifyPropertyChanged interface
    30. Use the PropertyChanged event to make data binding work
    31. 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
  8. About the Authors

Product information

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