Book description
Go from beginner to confident developer as you create apps, games, and real-world projects using C#, .NET 9, and Visual Studio. With this engaging, visual guide, you'll master object-oriented programming, build 3D games in Unity, harness the power of LINQ for data queries, and learn to leverage AI tools in your development, through puzzles, hands-on exercises, and practical projects that stick. Dive right in and build a cross-platform game in chapter one using C# and .NET MAUI--running on Windows, macOS, Android, and iOS. Our readers have become professional developers, team leads, and coding streamers. No experience needed--just bring your desire to learn. This is where your coding journey begins.
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
Table of contents
- Related books from O’Reilly
- Table of Contents (the real thing)
- How to use this Book Intro
-
1. Start Building Apps with C# Build something great...fast!
- Learn C#...and learn to become a great developer
- Write code and explore C# with Visual Studio
- Install Visual Studio Community Edition
- Run Visual Studio
- Create and run your first C# project in Visual Studio
- You can use Visual Studio Code with Head First C#
- Install the C# extensions
- Create and run your first project in Visual Studio Code
- Set up Visual Studio Code for the next project
- Let’s build a game!
- Break up large projects into smaller parts
- Here’s how you’ll build your game
- Create a .NET MAUI project in Visual Studio
- Create a .NET MAUI project in Visual Studio Code
- Run your new .NET MAUI app
- MAUI apps work on all of your devices
- Here’s the page that you’ll build
- Start editing your XAML code
- Add the XAML for a Button and a Label
- Use a FlexLayout to make a grid of animal buttons
- Write C# code to add the animals to the buttons
- Start editing the PlayAgainButton event handler method
- Add more statements to your event handler
- Add animals to your buttons
- Run your app!
- Visual Studio makes it easy to use Git
- Add C# code to handle mouse clicks
- Enter the code for the event handler
- Run your app and find all the pairs
- Finish the game by adding a timer
- Add a timer to your game’s code
- Finish the code for your game
- Even better ifs...
-
2. Variables, Statements, and Methods Dive into C# code
- Take a closer look at the files in your console app
- Statements are the building blocks for your apps
- Statements live inside methods
- Your methods use variables to work with data
- Generate a new method to work with variables
- Add code that uses operators to your method
- Use the debugger to watch your variables change
- Use code snippets to help write loops
- Use operators to work with variables
- if statements make decisions
- Loops perform an action over and over
- Some useful things to keep in mind about C# code
- Controls drive the mechanics of your user interfaces
- Other controls you’ll use in this book
- Build a .NET MAUI app to experiment with controls
- Create a new app to experiment with controls
- Explore your new MAUI app and figure out how it works
- Add an Entry control to your app
- Add properties to your Entry control
- Make your Entry control update a Label control
- Combine horizontal and vertical stack layouts
- Add a Picker control to display a list of choices
-
Unity Lab #1 Explore C# with Unity
- Unity is a powerful tool for game design
- Download Unity Hub
- Use Unity Hub to create a new project
- Take control of the Unity layout
- Your scene is a 3D environment
- Unity games are made with GameObjects
- Use the Move Gizmo to move your GameObjects
- The Inspector shows your GameObject’s components
- Add a material to your Sphere GameObject
- Rotate your sphere
-
3. Namespaces and Classes Organizing your code
- Classes help you organize your code
- If code is useful, classes can help you reuse it
- Some methods take parameters and return a value
- Visual Studio helps you explore parameters and return values
- Let’s build an app that picks random cards
- You’ll use an array to store the cards
- Create an app with a Main method
- Add a class called CardPicker to your app
- Use Quick Actions to remove unnecessary using lines
- Convert between namespace styles
- Use the new keyword to create an array of strings
- Ana’s working on her next game
- Ana’s game is evolving...
- Build a paper prototype for a classic game
- Build a MAUI version of your random card app
- Make your MAUI app pick random cards
- Reuse your CardPicker class
- Add a using directive to use code in another namespace
- Ana’s prototypes look great...
- Ana can use objects to solve her problem
- You use a class to build an object
- When you create a new object from a class, it’s called an instance of that class
- A better solution for Ana...brought to you by objects
- An instance uses fields to keep track of things
- Thanks for the memory
- What’s on your app’s mind
- Sometimes code can be difficult to read
- Most code doesn’t come with a manual
- Use intuitive class and method names
- Build a class to work with some guys
- There’s an easier way to initialize objects with C#
- Use the C# Interactive window or csi to run C# code
-
4. Data, Types, Objects, and References Managing your app’s data
- Owen could use our help!
- Character sheets store different types of data on paper
- A variable’s type determines what kind of data it can store
- C# has several types for storing integers
- Types for storing really HUGE and really tiny numbers
- Let’s talk about strings
- A literal is a value written directly into your code
- A variable is like a data to-go cup
- Other types come in different sizes too
- 10 pounds of data in a 5-pound bag
- Casting lets you copy values that C# can’t automatically convert to another type
- C# does some conversions automatically
- When you call a method, the arguments need to be compatible with the types of the parameters
- Owen is constantly improving his game...
- Let’s help Owen experiment with ability scores
- Fix the compiler error by adding a cast
- Use reference variables to access your objects
- References are like sticky notes for your objects
- If there aren’t any more references, your object gets garbage-collected
- Multiple references and their side effects
- Two references mean TWO variables that can change the same object’s data
- Objects use references to talk to each other
- Arrays hold multiple values
- Arrays can contain reference variables
- null means a reference points to nothing
- Use the string? type when a string might be null
- Welcome to Sloppy Joe’s Budget House o’ Discount Sandwiches!
- Sloppy Joe’s menu app uses a Grid layout
- Grid controls
- Define the rows and columns for a Grid
- Create the Sloppy Joe’s menu app and set up the grid
- The C# code for the main page
- Can we make the app more accessible?
- Use the SetValue method to change a control’s semantic properties
-
Unity Lab #2 Write C# Code for Unity
- C# scripts add behavior to your GameObjects
- Add a C# script to your GameObject
- Write C# code to rotate your sphere
- Add a breakpoint and debug your game
- Use the debugger to understand Time.deltaTime
- Add a cylinder to show where the Y axis is
- Add fields to your class for the rotation angle and speed
- Use Debug.DrawRay to explore how 3D vectors work
- Run the game to see the ray in the Scene view
- Rotate your ball around a point in the scene
- Use Unity to take a closer look at rotation and vectors
- Get creative!
-
5. Encapsulation How objects keep their Secrets
- Let’s help Owen roll for damage
- Create a console app to calculate damage
- Design a MAUI version of the damage calculator app
- Tabletop talk (or maybe...dice discussion?)
- Let’s try to fix that bug
- Use Debug.WriteLine to print diagnostic information
- It’s easy to accidentally misuse your objects
- Encapsulation means keeping some data in a class private
- Use encapsulation to control access to your class’s methods and fields
- But is the RealName field REALLY protected?
- Private fields and methods can only be accessed from instances of the same class
- Why encapsulation? Think of an object as an opaque box...
- Let’s use encapsulation to improve the SwordDamage class
- Encapsulation keeps your data safe
- Write a console app to test the PaintballGun class
- Properties make encapsulation easier
- Modify your top-level statements to use the Balls property
- Auto-implemented properties simplify your code
- Use a private setter to create a read-only property
- What if we want to change the magazine size?
- Use a constructor with parameters to initialize properties
- Specify arguments when you use the new keyword
- Initialize fields and properties inline or in the constructor
- Make the screen reader announce each roll
- A few useful facts about methods and properties
-
6. Inheritance Your Object’s Family Tree
- Calculate damage for MORE weapons
- Use a switch statement to match several candidates
- One more thing...can we calculate damage for a dagger? And a mace? And a staff? and...
- When your classes use inheritance, you only need to write your code once
- Build up your class model by starting general and getting more specific
- How would you design a zoo simulator?
- Different animals have different behaviors
- Every subclass extends its base class
- Any place where you can use a base class, you can use one of its subclasses instead
- Use a colon to extend a base class
- We know that inheritance adds the base class fields, properties, and methods to the subclass...
- A subclass can override methods to change or replace members it inherited
- Some members are only implemented in a subclass
- Use the debugger to understand how overriding works
- Build an app to explore virtual and override
- A subclass can hide methods in the base class
- Use the override and virtual keywords to inherit behavior
- A subclass can access its base class using the base keyword
- When a base class has a constructor, your subclass needs to call it
- A subclass and base class can have different constructors
- It’s time to finish the job for Owen
- A class should do one thing
- Build a beehive management system
- How the Beehive Management System app works
- The page uses a grid to lay out the controls for the UI
- The Beehive Management System class model
- All bees in the system extend the Bee class
- All the constants are in their own static class
- The worker bees extend the Bee class
- The Queen class: how she manages the worker bees
- Here’s the code-behind for MainPage.xaml.cs
- Feedback drives your beehive management game
- The Beehive Management System is turn-based... now let’s convert it to real-time
- Some classes should never be instantiated
- An abstract class is an intentionally incomplete class
- Like we said, some classes should never be instantiated
- An abstract method doesn’t have a body
- Abstract properties work just like abstract methods
- The Deadly Diamond of Death
-
Unity Lab #3 GameObject Instances
- Let’s build a game in Unity!
- Create a new material inside the Materials folder
- Spawn a billiard ball at a random point in the scene
- Use the debugger to understand Random.value
- Turn your GameObject into a prefab
- Create a script to control the game
- Attach the GameController script to the Main Camera
- Press Play to run your code
- Use the Inspector to work with GameObject instances
- Use physics to keep balls from overlapping
- Get creative!
-
7. Interfaces, Casting, and “is” Making classes keep their Promises
- The beehive is under attack!
- We could use casting to call the DefendHive method…
- An interface defines methods and properties that a class must implement…
- Interfaces let unrelated classes do the same job
- Get a little practice using interfaces
- Fireside Chats
- You can’t instantiate an interface, but you can reference an interface
- Pool Puzzle
- Pool Puzzle Solution
- Interface references are ordinary object references
- The RoboBee 4000 can do a worker bee’s job without using valuable honey
- The IWorker’s Job property is a hack
- Use is to check the type of an object
- Use is to access methods in a subclass
- What if we want different animals to swim or hunt in packs?
- Use interfaces to work with classes that do the same job
- Safely navigate your class hierarchy with is
- C# has another tool for safe type conversion: the as keyword
- Use upcasting and downcasting to move up and down a class hierarchy
- A quick example of upcasting
- Upcasting turns your CoffeeMaker into an Appliance
- Downcasting turns your Appliance back into a CoffeeMaker
- Upcasting and downcasting work with interfaces too
- Interfaces can inherit from other interfaces
- Interfaces can have static members
- Default implementations give bodies to interface methods
- Add a ScareAdults method with a default implementation
- Data binding updates MAUI controls automatically
- Add data binding to the default MAUI app
- Make Moods implement the INotifyPropertyChanged interface
- Use the PropertyChanged event to make data binding work
- Polymorphism means that one object can take many different forms
-
8. Enums and Collections Organizing your data
- If a constructor just sets fields, use a primary constructor instead
- A primary constructor can extend a base constructor
- Strings don’t always work for storing categories of data
- Enums let you work with a set of valid values
- Enums let you represent numbers with names
- We could use an array to create a deck of cards…
- Arrays can be annoying to work with
- Lists make it easy to store collections of…anything
- Lists are more flexible than arrays
- Let’s build an app to store shoes
- Generic collections can store any type
- You can use collection expressions to create Lists
- Let’s create a List of Ducks
- Sorting lists can be tricky
- IComparable<Duck> helps your List sort its Ducks
- Use IComparer to tell your List how to sort
- Create an instance of your comparer object
- Comparers can do complex comparisons
- Overriding a ToString method lets an object describe itself
- Update your foreach loops to let your Ducks and Cards write themselves to the console
- You can upcast an entire list using IEnumerable<T>
- Use a Dictionary to store keys and values
- The Dictionary functionality rundown
- Write an app that uses a Dictionary
- And yet MORE collection types…
- A queue is FIFO—first in, first out
- A stack is LIFO—last in, first out
- CollectionView is a MAUI control built for displaying collections
- ObservableCollection is a collection made for data binding
- Add your Card class to the project
- Use XAML to instantiate your objects for data binding
- Modify your app to use a resource Dictionary
- Modify the event handlers to use the resource Dictionary
- Use what you’ve learned to build an app with two decks
-
Unity Lab #4 User Interfaces
- Add a score that goes up when the player clicks a ball
- Add two different modes to your game
- Add game mode to your game
- Add a UI to your game
- Set up the Text that will display the score in the UI
- Add a Button that calls a method to start the game
- Make the Play Again button and Score Text work
- Finish the code for the game
- Get creative!
-
9. LINQ and Lambdas Get Control of your data
- Jimmy’s a Captain Amazing superfan...
- ...but his collection’s all over the place
- Use LINQ to query your collections
- LINQ works with any sequence
- LINQ’s query syntax
- LINQ works with objects
- Use a LINQ query to finish the app for Jimmy
- The var keyword lets C# figure out variable types for you
- LINQ is versatile
- LINQ queries aren’t run until you access their results
- Use a group query to separate your sequence into groups
- Use join queries to merge data from two sequences
- Use the new keyword to create anonymous types
- Unit tests help you make sure your code works
- Start writing your first test method
- Give your unit tests access to the classes they’re testing
- One project can only access public classes in another project
- Use the Arrange-Act-Assert pattern to write an effective test
- Finish your first unit test
- Write a unit test for the GetReviews method
- Write unit tests to handle edge cases and weird data
- Use the => operator to create lambda expressions
- Refactor a clown with lambdas
- Use the ?: operator to make your lambdas make choices
- LINQ queries are made up of methods
- LINQ declarative syntax can be refactored into chained methods
- Use the => operator to create switch expressions
- Explore the Enumerable class
- Create an enumerable sequence by hand
- Use yield return to create your own sequences
- Use yield return to refactor ManualSportSequence
- Collectioncross
- Collectioncross solution
-
10. Reading and Writing Files Save the last byte for me
- .NET uses streams to read and write data
- Different streams read and write different things
- A FileStream reads and writes bytes in a file
- Write text to a file in three simple steps
- The Swindler launches another diabolical plan
- StreamWriter Magnets
- StreamWriter Magnets Solution
- Use a StreamReader to read a file
- Data can go through more than one stream
- Use the static File and Directory classes to work with files and directories
- IDisposable makes sure objects are closed properly
- Avoid filesystem errors with using statements
- Use a MemoryStream to stream data to memory
- What happens to an object when it’s serialized?
- But what exactly IS an object’s state? What needs to be saved?
- When an object is serialized, all of the objects it refers to get serialized too…
- Use JsonSerializer to serialize your objects
- JSON only includes data, not specific C# types
- Next up: we’ll take a deep dive into our data
- C# strings are encoded with Unicode
- Visual Studio works really well with Unicode
- .NET uses Unicode to store characters and text
- C# can use byte arrays to move data around
- Use a BinaryWriter to write binary data
- Use BinaryReader to read the data back in
- A hex dump lets you see the bytes in your files
- Use StreamReader to build a hex dumper
- Use Stream.Read to read bytes from a stream
- Modify your hex dumper to read directly from the stream
- Run your app from the command line
- Pass command-line arguments to an app run in the IDE
- Unity Lab #5 Raycasting
-
11. Captain Amazing the Death of the Object
- The life and death of an object
- Use the GC class (with caution) to force garbage collection
- Your last chance to DO something... your object’s finalizer
- When EXACTLY does a finalizer run?
- Finalizers can’t depend on other objects
- A struct looks like an object...
- Values get copied; references get assigned
- Structs are value types; objects are reference types
- The stack vs. the heap: more on memory
- Use out parameters to make a method return more than one value
- Pass by reference using the ref modifier
- Use optional parameters to set default values
- A null reference doesn’t refer to any object
- Non-nullable reference types help you avoid NREs
- Nullable value types can be null...and handled safely
- The null-coalescing operator ?? checks for nulls automatically
- “Captain” Amazing...not so much
- Records give your objects value equality automatically
- Don’t modify records—copy them
- Extension methods add new behavior to EXISTING classes
- Extending a fundamental type: string
-
12. Exception Handling Putting out fires gets old
- Your hex dumper reads a filename from the command line
- When your program throws an exception, the CLR generates an Exception object
- All Exception objects inherit from System.Exception
- There are some files you just can’t dump
- What happens when a method you want to call is risky?
- Handle exceptions with try and catch
- Use the debugger to follow the try/catch flow
- If you have code that ALWAYS needs to run, use a finally block
- Catch-all exceptions handle System.Exception
- Pool Puzzle
- Pool Puzzle Solution
- Use the right exception for the situation
- Exception Magnets
- Exception Magnets Solution
- Exception filters help you create precise handlers
- The worst catch block EVER: catch-all plus comments
- Temporary solutions are OK (temporarily)
- Use NuGet to add a logging library to your app
- Add logging to your ExceptionExperiment app
- Unity Lab #6 Scene Navigation
- Index
- The Authors
Product information
- Title: Head First C#, 5th Edition
- Author(s):
- Release date: July 2024
- Publisher(s): O'Reilly Media, Inc.
- ISBN: 9781098141783
You might also like
book
Head First C#, 4th Edition
What will you learn from this book? Dive into C# and create apps, user interfaces, games, …
book
C# 12 and .NET 8 – Modern Cross-Platform Development Fundamentals - Eighth Edition
An accessible guide for beginner-to-intermediate programmers to the concepts, real-world applications, and latest features of C# …
book
Head First Go
What will you learn from this book? Go makes it easy to build software that’s simple, …
book
C# 12 in a Nutshell
When you have questions about C# 12 or .NET 8, this best-selling guide has the answers …