Book description
What will you learn from this book?
Dive into C# and create apps, user interfaces, games, and more using this fun and highly visual introduction to C#, .NET Core, and Visual Studio. With this completely updated guide, which covers C# 8.0 and Visual Studio 2019, beginning programmers like you will build a fully functional game in the opening chapter. Then 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. By the time you're done, you'll be a solid C# programmer--and you'll have a great time along the way!
What's so special about this book?
Based on the latest research in cognitive science and learning theory, Head First C# uses a visually rich format to engage your mind rather than a text-heavy approach that puts you to sleep. Why waste your time struggling with new concepts? This multisensory learning experience is designed for the way your brain really works.
Publisher resources
Table of contents
- The Authors
- Intro: How to use this book
-
1. Start Building with C#: Build something great…fast!
- Why you should learn C#
- Visual Studio is a tool for writing code and exploring C#
- Create your first project in Visual Studio
- Let’s build a game!
- Here’s how you’ll build your game
- Create a WPF project in Visual Studio
- Use XAML to design your window
- Design the window for your game
- Set the window size and title with XAML properties
- Add rows and columns to the XAML grid
- Make the rows and columns equal size
- Add a TextBlock control to your grid
- Now you’re ready to start writing code for your game
- Generate a method to set up the game
- Finish your SetUpGame method
- Run your program
- Add your new project to source control
- The next step to build the game is handling mouse clicks
- Make your TextBlocks respond to mouse clicks
- Add the TextBlock_MouseDown code
- Make the rest of the TextBlocks call the same MouseDown event handler
- Finish the game by adding a timer
- Add a timer to your game’s code
- Use the debugger to troubleshoot the exception
- Add the rest of the code and finish the game
- Update your code in source control
- Even better ifs…
-
2. Dive into C#: Statements, Classes, and Code
- Let’s take a closer look at the files for a console app
- Two classes can be in the same namespace (and file!)
- Statements are the building blocks for your apps
- Your programs 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 operators to work with variables
- “if” statements make decisions
- Loops perform an action over and over
- Use code snippets to help write loops
- Controls drive the mechanics of your user interfaces
- Create a WPF app to experiment with controls
- Add a TextBox control to your app
- Add C# code to update the TextBlock
- Add an event handler that only allows number input
- Add sliders to the bottom row of the grid
- Add C# code to make the rest of the controls work
-
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
- Make Visual Studio your Unity script editor
- Take control of the Unity layout
- Choose the Wide layout to match our screenshots
- 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
- Move the Scene view camera with the Hand tool and Scene Gizmo
- Get creative!
-
3. Objects…get oriented!: Making code make sense
- If code is useful, it gets reused
- Some methods take parameters and return a value
- Let’s build a program that picks some cards
- Create your PickRandomCards console app
- Finish your PickSomeCards method
- Your finished CardPicker class
- Ana’s working on her next game
- Build a paper prototype for a classic game
- Up next: build a WPF version of your card picking app
- A StackPanel is a container that stacks other controls
- Reuse your CardPicker class in a new WPF app
- Use a Grid and StackPanel to lay out the main window
- Lay out your Card Picker desktop app’s window
- 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 program’s mind
- Sometimes code can be difficult to read
- 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 to run C# code
-
4. Types and References: Getting the Reference
- 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
- 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
- Let’s help Owen experiment with ability scores
- Use the C# compiler to find the problematic line of code
- Use reference variables to access your objects
- Multiple references and their side effects
- Objects use references to talk to each other
- Arrays hold multiple values
- Arrays can contain reference variables
- null means a reference points to nothing
- Welcome to Sloppy Joe’s Budget House o’ Discount Sandwiches!
-
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 a hit count to skip frames
- 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
- Use Unity to visualize vectors in 3D
- Run the game to see the ray in the Scene view
- Add a duration to the ray so it leaves a trail
- Rotate your ball around a point in the scene
- Use Unity to take a closer look at rotation and vectors
- Get creative!
-
5. Encapsulation: Keep your Privates… Private
- Let’s help Owen roll for damage
- Create a console app to calculate damage
- Design the XAML for a WPF version of the damage calculator
- The code-behind for the WPF damage calculator
- 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 of the 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 a black 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 Main method 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
-
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
- When your classes overlap as little as possible, that’s an important design principle called separation of concerns
- Build a beehive management system
- The beehive management system class model
- The Queen class: how she manages the worker bees
- The UI: add the XAML for the main window
- 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
-
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 script to the Main Camera
- Press Play to run your code
- Watch the live instances in the Hierarchy window
- 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 can 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
- You can’t instantiate an interface, but you can reference an interface
- 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 WPF controls automatically
- Modify the Beehive Management System to use data binding
- Polymorphism means that one object can take many different forms
-
8. Enums and Collections: Organizing your Data
- 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
- Collection initializers are similar to object initializers
- Let’s create a List of Ducks
- Lists are easy, but SORTING 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
- Build a program 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
-
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
- Use the 2D view to work with the Canvas
- 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 super-fan...
- ...but his collection’s all over the place
- Use LINQ to query your collections
- LINQ works with any IEnumerable<T>
- 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
- Add a unit test project to Jimmy’s comic collection app
- Write 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
- A lambda test drive
- Refactor a clown with lambdas
- Use the ?: operator to make your lambdas make choices
- Lambda expressions and LINQ
- LINQ queries can be written as chained LINQ 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
- Pool Puzzle
- Pool Puzzle Solution
- 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 JsonSerialization 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 use command-line arguments
- 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
- The null-coalescing operator ?? helps with nulls
- Nullable value types can be null...and handled safely
- “Captain” Amazing...not so much
- Pool Puzzle
- Pool Puzzle Solution
- Extension methods add new behavior to EXISTING classes
- Extending a fundamental type: string
- Extension Magnets
- Extension Magnets Solution
-
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)
-
Unity Lab #6 Scene Navigation
- Let’s pick up where the last Unity Lab left off
- Add a platform to your scene
- Use bake options to make the platform walkable
- Include the stairs and ramp in your NavMesh
- Fix height problems in the NavMesh
- Add a NavMesh Obstacle
- Add a script to move the obstacle up and down
- Get creative!
- Downloadable exercise: Animal match boss battle
- Thank you for reading our book!
- But wait, there’s more! Your journey’s just begun...
- And check out these essential (and amazing!) books by some of our friends and colleagues, also published by O’REILLY
-
A. ASP.NET Core Blazor projects: Visual Studio for Mac Learner’s Guide
- Why you should learn C#
- Visual Studio is a tool for writing code and exploring C#
- Create your first project in Visual Studio for Mac
- Use the Visual Studio IDE to explore your app
- Let’s build a game!
- Here’s how you’ll build your game
- Create a Blazor WebAssembly App in Visual Studio
- Run your Blazor web app in a browser
- Now you’re ready to start writing code for your game
- Visual Studio helps you write C# code
- Finish creating your emoji list and display it in the app
- Shuffle the animals so they’re in a random order
- You’re running your game in the debugger
- Add your new project to source control
- Add C# code to handle mouse clicks
- Add click event handlers to your buttons
- Test your event handler
- Use the debugger to troubleshoot the problem
- Keep debugging your event handler
- Track down the bug that’s causing the problem...
- Add code to reset the game when the player wins
- Finish the game by adding a timer
- Add a timer to your game’s code
- Clean up the navigation menu
- Even better ifs...
- from Chapter 2 dive into C#
- Controls drive the mechanics of your user interfaces
- Create a new Blazor WebAssembly App project
- Create a page with a slider control
- Add a text input to your app
- Add color and date pickers to your app
- from Chapter 3 objects...get oriented!
- Up next: build a Blazor version of your card picking app
- The page is laid out with rows and columns
- The slider uses data binding to update a variable
- from Chapter 4 types and references
- B. Code Kata Guide for the Advanced and/or Impatient
- Index
Product information
- Title: Head First C#, 4th Edition
- Author(s):
- Release date: December 2020
- Publisher(s): O'Reilly Media, Inc.
- ISBN: 9781491976708
You might also like
book
Head First C#, 5th Edition
What will you learn from this book? Create apps, games, and more using this engaging, highly …
book
Learn C# Programming
Get started with C# and strengthen your knowledge of core programming concepts such as procedural, object-oriented, …
book
C# 6 for Programmers, Sixth Edition
The professional programmer’s Deitel® guide to C# 6 and object-oriented development for Windows® Written for programmers …
book
CLR via C#, Fourth Edition
Dig deep and master the intricacies of the common language runtime, C#, and .NET development. Led …