0%

Book Description

What will you learn from this book?

Ready to dive into C#? This practical guide provides beginning programmers with a fun and highly visual introduction to C#, XAML, .NET Core, and Visual Studio. You’ll quickly learn C# fundamentals, including how this language helps you create user interfaces, databases, and more. With this latest edition, you’ll build a fully functional game in the opening chapter and then learn how to use classes and object-oriented programming, draw graphics and animation, and query data with LINQ. And you’ll do it all by creating games, solving puzzles, and doing hands-on projects. By the time you’re done, you’ll be a solid C# programmer—and you’ll have a great time along the way!

  • Dive right in—build a game with C# in the first chapter
  • Learn how to use XAML to design attractive and interactive pages and windows
  • Use any edition of Visual Studio to practice your C# coding skills in dozens of projects
  • Create cross-platform apps and build native macOS apps using Visual Studio 2019 for Mac
  • Develop 3D games and simulations in specially designed Unity labs using C# tools, techniques, and concepts

Why does this book look so different?

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.

Table of Contents

  1. 1. Start Building with c#: Build Something Great... Fast!
    1. Why you should learn C#
      1. Visual Studio is your gateway to C#
    2. Visual Studio is a tool for writing code and exploring C#
    3. Create your first project in Visual Studio
    4. Let’s build a game!
      1. Your animal match game is a WPF app
    5. Here’s how you’ll build your game
    6. Create a WPF project in Visual Studio
      1. Visual Studio created a project folder full of files for you
    7. Use XAML to design your window
    8. Design the window for your game
    9. Set the window size and title with XAML properties
    10. Add rows and columns to the XAML grid
    11. Make the rows and columns equal size
    12. Add a TextBlock control to your Grid
    13. Now you’re ready to start writing code for your game
    14. Generate a method to set up the game
    15. Finish your SetUpGame method
    16. Run your program
    17. Add your new project to source control
    18. The next step to build the game is handling mouse clicks
    19. Make your TextBlocks respond to mouse clicks
    20. Add the TextBlock_MouseDown code
    21. Make the rest of the TextBlocks call the same MouseDown event handler
    22. Finish the game by adding a timer
    23. Add a timer to your game’s code
    24. Use the debugger to troubleshoot the exception
    25. Add the rest of the code and finish the game
    26. Update your code in source control
    27. Even better if’s...
  2. 2. Dive Into C#: Statements, Classes, and Code
    1. Let’s take a closer look at the files for a console app
      1. A statement performs one single action
    2. Two classes can be in the same namespace (and file!)
      1. The IDE helps you build your code right.
    3. Statements are the building blocks for your apps
    4. Your programs 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 help to write loops
    12. Some useful things to keep in mind about C# code
    13. Controls drive the mechanics of your user interfaces
    14. Create a WPF app to experiment with controls
    15. Add a TextBox control to your app
    16. Add C# code to update the TextBlock
    17. Add an event handler that only allows number input
    18. Add sliders to the bottom row of the grid
    19. Add C# code to make the rest of the controls work
  3. I. Unity Lab 1: Start Exploring Unity
  4. 3. Objects... Get Oriented! Making code make sense
    1. If code is useful, it gets reused
    2. Some methods return a value
    3. Let’s build a program that picks some cards
      1. string[] cards = PickSomeCards(5);
    4. Create your PickRandomCards console app
    5. Finish your PickSomeCards method
    6. Your finished CardPicker class
    7. Ana’s working on her next game
    8. Ana’s game is evolving...
    9. ... so how can Ana make things easier for herself?
    10. Build a simple paper prototype for a classic game
    11. Up next: build a WPF version of your card picking app
    12. A StackPanel is a container that stacks other controls
    13. Reuse your CardPicker class in a new WPF app
    14. Use a Grid and StackPanel to lay out the main window
    15. Lay out your Card Picker desktop app’s window
    16. Ana’s prototypes look great...
    17. Ana can use objects to solve her problem
    18. You use a class to build an object
      1. An object gets its methods from its class
    19. When you create a new object from a class, it’s called an instance of that class
    20. A better solution for Ana... brought to you by objects
    21. Theory and practice
    22. An instance uses fields to keep track of things
    23. Methods are what an object does. Fields are what the object knows.
    24. Thanks for the memory
    25. What’s on your program’s mind
    26. Sometimes code can be difficult to read
    27. 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 to run C# code
  5. 4. Types and References: Getting the Reference
    1. Ryan is looking to improve his game
      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 whole numbers
    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?
    12. When you cast a value that’s too big, C# adjusts it to fit its new container
    13. C# does some conversion automatically
    14. When you call a method, the arguments need to be compatible with the types of the parameters
    15. Ryan is constantly improving his game
    16. Let’s help Ryan experiment with ability scores
    17. And now we can finally fix Ryan’s bug
    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
    27. A Random Test Drive
    28. Welcome to Sloppy Joe’s Budget House o’ Discount Sandwiches!
  6. II. Unity Lab 2: Write C# Code for Unity
  7. 5. Encapsulation: Keep your privates... private
    1. Let’s help Ryan roll for damage
    2. Create a console app to calculate damage
    3. Design the XAML for a WPF version of the damage calculator
    4. The code-behind for the WPF damage calculator
    5. Tabletop talk (or maybe... dice discussion?)
    6. Let’s try to fix that bug
    7. Use Debug.WriteLine to print diagnostic information
    8. It’s easy to accidentally misuse your objects
    9. Encapsulation means keeping some of the data in a class private
    10. Use encapsulation to control access to your class’s methods and fields
    11. But is the RealName field REALLY protected?
    12. Private fields and methods can only be accessed from instances of the same class
    13. Think of an object as a black box
      1. Encapsulation makes your classes...
    14. A few ideas for encapsulating classes
    15. 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?
    16. Encapsulation keeps your data safe
      1. Let’s use encapsulation in a simple class
    17. Write a console app to test the MachineGun class
      1. Our class is well-encapsulated, but...
    18. Properties make encapsulation easier
      1. Replace the GetBullets and SetBullets methods with a property
    19. Modify your Main method to use the Bullets property
      1. Debug your MachineGun class to understand how the property works
    20. Auto-implemented properties simplify your code
      1. Use the prop snippet to create an auto-implemented property
    21. Use a private setter to create a read-only property
      1. Make the BulletsLoaded setter private
    22. What if we want to change the magazine size?
      1. But there’s a problem... how do we initialize MagazineSize?
    23. Use a constructor with parameters to initialize properties
    24. Specify arguments when you use the new keyword
    25. A few useful facts about methods and properties
    26. Objectcross
    27. Objectcross solution
  8. 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. Use inheritance to avoid duplicate code in subclasses
    8. Different animals make different noises
      1. Think about what you need to override
    9. Think about how to group the animals
    10. Create the class hierarchy
    11. Every subclass extends its base class
      1. C# always calls the most specific method
    12. Any place where you can use a base class, you can use one of its subclasses instead
    13. Use a colon to extend a base class
    14. We know that inheritance adds the base class fields, properties, and methods to the subclass...
      1. ...but some birds don’t fly!
    15. A subclass can override methods to change or replace members it inherited
    16. Some members are only implemented in a subclass
    17. Use the debugger to understand how overriding works
    18. Build an app to explore virtual and override
    19. A subclass can hide methods in the superclass
      1. Hiding methods versus overriding methods
      2. Use the new keyword when you’re hiding methods
      3. Use different references to call hidden methods
    20. Use the override and virtual keywords to inherit behavior
    21. A subclass can access its base class using the base keyword
    22. When a base class has a constructor, your subclass needs to call it
    23. A subclass and base class can have different constructors
    24. It’s time to finish the job for Ryan
    25. When your classes overlap as little as possible, that’s an important design principle called separation of concerns
      1. Use the debugger to really understand how these classes work
    26. Build a beehive management system
    27. The beehive management system class model
    28. The UI: add the XAML for the main window
    29. The Queen class: how she manages the worker bees
    30. Feedback drives your Beehive Management game
      1. Workers and honey are in a feedback loop
    31. Your game is turn-based... now let’s convert it to a real-time game
    32. Some classes should never be instantiated
    33. An abstract class is an intentionally incomplete class
    34. Like we said, some classes should never be instantiated
      1. Solution: use an abstract class
    35. An abstract method doesn’t have a body
    36. Abstract properties work just like abstract methods
    37. The Deadly Diamond of Death
  9. III. Unity Lab 3: GameObject Instances
  10. 7. Interfaces, Casting, and “is” Making Classes keep their Promises
    1. The beehive is under attack!
      1. So we need a DefendHive method, because enemies can attack at any time
      2. We can use casting to call the DefendHive method...
      3. ... but what if we add more Bee subclasses that can defend?
      4. An interface defines methods and properties that a class must implement...
      5. ... but there’s no limit on interfaces that a class can implement
      6. Interfaces let unrelated classes do the same job
      7. Get a little practice using interfaces
    2. 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. ...but use the interface to reference an object you already have
    3. Interface references are ordinary object references
    4. The RoboBee 4000 can do a worker bee’s job without using valuable honey
    5. The IWorker’s Job propert y is a hack
    6. Use “is” to check the t ype of an object
    7. Use the “is” keyword to access methods in a subclass
    8. What if we want different animals to swim or hunt in packs?
    9. Use interfaces to you work with classes that do the same job
      1. Use the is keyword to check if the Animal is a swimmer or pack hunter
    10. C# helps you safely navigate your class hierarchy
    11. C# has another tool for safe type conversion: the as keyword
    12. Use upcasting and downcasting to move up and down a class hierarchy
    13. A CoffeeMaker is also an Appliance
    14. Upcasting turns your CoffeeMaker into an Appliance
    15. Downcasting turns your Appliance back into a CoffeeMaker
    16. Upcasting and downcasting work with interfaces, too
    17. Interfaces can inherit from other interfaces
    18. Interfaces static members work exactly like in classes
    19. Default implementations give bodies to interface methods
    20. Add a ScareAdults method with a default implementation
    21. Data binding updates WPF controls automatically
    22. Modify the beehive management system to use data binding
    23. 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
    24. OOPcross
    25. OOPcross Solution
  11. 8. Enums and Collections Organizing your data
    1. Strings don’t always work for storing categories of data
    2. Enums let you work with a set of valid values
      1. An enum defines a new type
    3. Enums let you represent numbers with names
    4. We could use an array to create a deck of cards…
      1. …but what if you wanted to do more?
    5. Arrays can be annoying to work with
    6. Lists make it easy to store collections of… anything
    7. Lists are more flexible than arrays
    8. Let’s build an app to store shoes
    9. Generic collections can store any type
      1. Generic lists are declared using <angle brackets>
    10. Code Magnets
    11. Code Magnets Solution
    12. Collection initializers are similar to object initializers
    13. Let’s create a List of Ducks
      1. Here’s the initializer for your List of Ducks
    14. Lists are easy, but SORTING 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
    20. Override the ToString method to see your Ducks in the IDE
    21. Update your foreach loops to let your Ducks and Cards print themselves
      1. Add a ToString method to your Card object, too
    22. You can upcast an entire list using IEnumerable<T>
    23. Use a Dictionary to store keys and values
    24. The Dictionary functionalit y rundown
    25. Your key and value can be different types
    26. Build a program that uses a dictionary
    27. And yet MORE collection t ypes…
    28. Generic .NET collections implement IEnumerable
    29. A queue is FIFO—First In, First Out
    30. A stack is LIFO—Last In, First Out
    31. Let’s build an app to work with decks of cards
    32. Add a Deck class to hold the cards
      1. Create a Deck that extends Obser vableCollection
      2. Add a Window.Resources with t wo instances of the Deck class
    33. Use Visual Studio to set up data binding
  12. IV. Unity Lab 4: User Interfaces
  13. 9. LINQ and Lambdas Get Control of your data
    1. Jimmy’s a Captain Amazing super-fan...
    2. …but his collection’s all over the place
    3. Use LINQ to query your collections
    4. LINQ works with any IEnumerable<T>
      1. LINQ methods enumerate your sequences
    5. LINQ works with objects
    6. LINQ’s query syntax
    7. Anatomy of a query
    8. The var keyword lets C# figure out variable t ypes for you
    9. When you use var, C# figures out the variable’s type automatically
    10. LINQ magnets
    11. LINQ Magnets Solution
    12. LINQ is versatile
    13. LINQ queries aren’t run until you access their results
    14. Use a group query to separate your sequence into groups
    15. Anatomy of a group query
    16. Use join queries to merge data from t wo sequences
    17. Use the new keyword to create anonymous types
    18. Unit tests help you make sure your code works
      1. Visual Studio for Windows has the Test Explorer window
      2. Visual Studio for Mac has the Unit Test pad
    19. Add a unit test project to your solutionAdd
    20. Write your first unit test
    21. Write a unit test for the GetReviews method
    22. Write unit tests to handle edge cases and weird data
    23. Use the => operator to create lambda expressions
    24. A Lambda Test Drive
    25. Refactor a clown with lambdas
    26. Use the ?: operator to make your lambdas make choices
    27. Lambda expressions and LINQ
    28. Use lambda expressions with methods that take a Func parameter
    29. LINQ queries can be written as chained LINQ methods
      1. The OrderBy LINQ method sorts a sequence
      2. The Where LINQ method pulls out a subset of a sequence
    30. Use the => operator to create switch expressions
    31. Explore the Enumerable class
      1. Enumerable.Empty creates an empty sequence of any type
      2. Enumerable.Repeat repeats a value a number of times
      3. So what exactly is an IEnumerable<T>?
    32. Create an enumerable sequence by hand
    33. Use yield return to create your own sequences
    34. Use the debugger to explore yield return
    35. Use yield return to refactor ManualSportSequence
      1. Add an indexer to BetterSportSequence
    36. Collectioncross
    37. Collectioncross solution
  14. 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 to a file
    4. Write text to a file in three simple steps
    5. The Swindler launches another diabolical plan
    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. Pool Puzzle
    11. Pool Puzzle Solution
    12. Use the File and Directory classes to work with files and directories
    13. IDisposable makes sure objects are closed properly
      1. Use the IDE to explore IDisposable
    14. Avoid filesystem errors with using statements
      1. Use multiple using statements for multiple objects
    15. What happens to an object when it’s serialized?
    16. But what exactly IS an object’s state? What needs to be saved?
    17. When an object is serialized, all of the objects it refers to get serialized, too…
    18. Use JsonSerialization to serialize your objects
    19. JSON only includes data, not specific C# types
    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
    27. How to make a hex dump of some plain text
    28. Use SteamReader to build a simple hex dumper
    29. Use Stream.Read to read bytes from a stream
    30. Modify your hex dumper to use command-line arguments
  15. V. Unity Lab 5: Raycasting
  16. 11. Captain Amazing the Death of the Object
    1. The death of an object
    2. (DON’T) Use the GC class to work with the garbage collector
    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 stability
      1. Don’t use finalizers for serialization
    6. As truct 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. The null-coalescing operator ?? helps with nulls
      1. ?? checks for null and returns an alternative
    16. ??= assigns a value to a variable only if it’s null
    17. Nullable value types can be null – and handled safely
    18. “Captain” Amazing...not so much
    19. Pool Puzzle
    20. Pool Puzzle Solution
    21. Extension methods add new behavior to EXISTING classes
    22. Extending a fundamental type: string
    23. Extension Magnets
    24. Extension Magnets
  17. 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
    10. Avoid catch-all exception with multiple catch blocks
    11. Pool Puzzle
    12. Pool Puzzle Solution
    13. Use the right exception for the situation
    14. Catch custom exceptions that extend System.Exception
    15. Exception Magnets
    16. Exception Magnets Solution
    17. Exception filters help you create precise handlers
    18. The worst catch block EVER: catch-all plus comments
    19. You should handle your exceptions, not bury them
    20. Temporary solutions are OK (temporarily)
    21. Thank you for reading our book!
      1. But wait, there’s more! Your journey’s just begun...
      2. And check out these essential (and amazing!) books by some of our friends and colleagues, also published by O’REILLY®
  18. VI. Unity Lab 6: Scene Navigation
18.227.24.209