Safari, the world’s most comprehensive technology and business learning platform.

Find the exact information you need to solve a problem on the fly, or go deeper to master the technologies and skills you need to succeed

Start Free Trial

No credit card required

O'Reilly logo
Head First C#, 3rd Edition

Book Description

Head First C# is a complete learning experience for learning how to program with C#, XAML, the .NET Framework, and Visual Studio. Fun and highly visual, this introduction to C# is designed to keep you engaged and entertained from first page to last.

Table of Contents

  1. Head First C#
  2. Dedication
  3. A Note Regarding Supplemental Files
  4. Head First C#
    1. What will you learn from this book?
    2. Why does this book look so different?
  5. Advance Praise for Head First C#
  6. Praise for other Head First books
  8. 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. And 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. What you need for this book
      1. You do not need Windows 8 to use this book!
    8. Read me
    9. The technical review team
    10. Acknowledgments
    11. Safari® Books Online
  9. 1. Start Building With c#: Build something cool, fast!
    1. Why you should learn C#
      1. Here’s what the IDE automates for you...
      2. What you get with Visual Studio and C#...
    2. C# and the Visual Studio IDE make lots of things easy
    3. What you do in Visual Studio...
    4. What Visual Studio does for you...
    5. Aliens attack!
    6. Only you can help save the Earth
    7. Here’s what you’re going to build
    8. Start with a blank application
    9. Set up the grid for your page
    10. Add controls to your grid
    11. Use properties to change how the controls look
    12. Controls make the game work
    13. You’ve set the stage for the game
    14. What you’ll do next
    15. Add a method that does something
      1. Use the IDE to create your own method
    16. Fill in the code for your method
    17. Finish the method and run your program
    18. Here’s what you’ve done so far
    19. Add timers to manage the gameplay
    20. Make the Start button work
    21. Run the program to see your progress
    22. Add code to make your controls interact with the player
    23. Dragging humans onto enemies ends the game
    24. Your game is now playable
    25. Make your enemies look like aliens
    26. Add a splash screen and a tile
    27. Publish your app
    28. Use the Remote Debugger to sideload your app
    29. Start remote debugging
  10. 2. It’s all Just Code: Under the hood
    1. When you’re doing this...
    2. ...the IDE does this
    3. Where programs come from
      1. Every program starts out as source code files
      2. Build the program to create an executable
      3. The .NET Framework gives you the right tools for the job
      4. Your program runs inside the Common Language Runtime
    4. The IDE helps you code
    5. Anatomy of a program
      1. Let’s take a closer look at your code
    6. Two classes can be in the same namespace
    7. Your programs use variables to work with data
      1. Declare your variables
      2. Variables vary
      3. You have to assign values to variables before you use them
      4. A few useful types
    8. C# uses familiar math symbols
    9. Use the debugger to see your variables change
    10. Loops perform an action over and over
      1. Use a code snippet to write simple for loops
    11. if/else statements make decisions
    12. Build an app from the ground up
    13. Make each button do something
    14. Set up conditions and see if they’re true
      1. Use logical operators to check conditions
    15. Windows Desktop apps are easy to build
    16. Rebuild your app for Windows Desktop
    17. Your desktop app knows where to start
    18. You can change your program’s entry point
      1. So what happened?
    19. When you change things in the IDE, you’re also changing your code
      1. Wait, wait! What did that say?
  11. 3. Objects: Get Oriented!: Making code make sense
    1. How Mike thinks about his problems
    2. How Mike’s car navigation system thinks about his problems
    3. Mike’s Navigator class has methods to set and modify routes
      1. Some methods have a return value
    4. Use what you’ve learned to build a program that uses a class
      1. So what did you just build?
    5. Mike gets an idea
      1. He could create three different Navigator classes...
    6. Mike can use objects to solve his problem
    7. You use a class to build an object
      1. An object gets its methods from its class
    8. When you create a new object from a class, it’s called an instance of that class
    9. A better solution...brought to you by objects!
      1. Theory and practice
      2. A little advice for the code exercises
    10. An instance uses fields to keep track of things
      1. Methods are what an object does. Fields are what the object knows.
    11. Let’s create some instances!
    12. Thanks for the memory
    13. What’s on your program’s mind
    14. You can use class and method names to make your code intuitive
    15. Give your classes a natural structure
      1. Let’s build a class diagram
    16. Class diagrams help you organize your classes so they make sense
    17. Build a class to work with some guys
    18. Create a project for your guys
    19. Build a form to interact with the guys
    20. There’s an easier way to initialize objects
    21. A few ideas for designing intuitive classes
  12. 4. Types and References: It’s 10:00. Do you know where your data is?
    1. The variable’s type determines what kind of data it can store
    2. A variable is like a data to-go cup
    3. 10 pounds of data in a 5-pound bag
    4. Even when a number is the right size, you can’t just assign it to any variable
      1. So what happened?
    5. When you cast a value that’s too big, C# will adjust it automatically
    6. C# does some casting automatically
    7. When you call a method, the arguments must be compatible with the types of the parameters
    8. Debug the mileage calculator
    9. Combining = with an operator
    10. Objects use variables, too
    11. Refer to your objects with reference variables
    12. References are like labels for your object
    13. If there aren’t any more references, your object gets garbage-collected
    14. Multiple references and their side effects
    15. Two references means TWO ways to change an object’s data
    16. A special case: arrays
      1. Use each element in an array like it is a normal variable
    17. Arrays can contain a bunch of reference variables, too
    18. Welcome to Sloppy Joe’s Budget House o’ Discount Sandwiches!
    19. Objects use references to talk to each other
    20. Where no object has gone before
    21. Build a typing game
    22. Controls are objects, just like any other object
  13. I. C# Lab: A Day at the Races
    1. 5. Encapsulation: Keep your privates... private
      1. Kathleen is an event planner
      2. What does the estimator do?
      3. You’re going to build a program for Kathleen
      4. Kathleen’s test drive
      5. Each option should be calculated individually
      6. It’s easy to accidentally misuse your objects
      7. Encapsulation means keeping some of the data in a class private
      8. Use encapsulation to control access to your class’s methods and fields
      9. But is the RealName field REALLY protected?
      10. Private fields and methods can only be accessed from inside the class
        1. Encapsulation makes your classes...
        2. Mike’s navigator program could use better encapsulation
        3. Think of an object as a black box
      11. A few ideas for encapsulating classes
      12. Encapsulation keeps your data pristine
        1. A quick example of encapsulation
      13. Properties make encapsulation easier
      14. Build an application to test the Farmer class
      15. Use automatic properties to finish the class
        1. Fully encapsulate the Farmer class
      16. What if we want to change the feed multiplier?
      17. Use a constructor to initialize private fields
    2. 6. Inheritance: Your object’s family tree
      1. Kathleen does birthday parties, too
      2. We need a BirthdayParty class
        1. Here’s what we’re going to do:
      3. Build the Party Planner version 2.0
      4. One more thing...can you add a $100 fee for parties over 12?
      5. When your classes use inheritance, you only need to write your code once
        1. Dinner parties and birthday parties are both parties
      6. Build up your class model by starting general and getting more specific
      7. How would you design a zoo simulator?
      8. Use inheritance to avoid duplicate code in subclasses
      9. Different animals make different noises
        1. Think about what you need to override
      10. Think about how to group the animals
      11. Create the class hierarchy
      12. Every subclass extends its base class
        1. C# always calls the most specific method
      13. Use a colon to inherit from 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 methods it inherited
      16. Any place where you can use a base class, you can use one of its subclasses instead
      17. A subclass can hide methods in the superclass
        1. Hiding methods versus overriding methods
        2. Use different references to call hidden methods
        3. Use the new keyword when you’re hiding methods
      18. Use the override and virtual keywords to inherit behavior
      19. A subclass can access its base class using the base keyword
      20. When a base class has a constructor, your subclass needs one, too
        1. The base class constructor is executed before the subclass constructor
      21. Now you’re ready to finish the job for Kathleen!
      22. Build a beehive management system
      23. How you’ll build the beehive management system
      24. Use inheritance to extend the bee management system
    3. 7. Interfaces and Abstract Classes: Making classes keep their promises
      1. Let’s get back to bee-sics
        1. Lots of things are still the same
      2. We can use inheritance to create classes for different types of bees
      3. An interface tells a class that it must implement certain methods and properties
      4. Use the interface keyword to define an interface
      5. Now you can create an instance of NectarStinger that does both jobs
      6. Classes that implement interfaces have to include ALL of the interface’s methods
      7. Get a little practice using interfaces
      8. You can’t instantiate an interface, but you can reference an interface
      9. Interface references work just like object references
      10. You can find out if a class implements a certain interface with “is”
      11. Interfaces can inherit from other interfaces
        1. Any class that implements an interface that inherits from IWorker must implement its methods and properties
      12. The RoboBee 4000 can do a worker bee’s job without using valuable honey
      13. is tells you what an object implements; as tells the compiler how to treat your object
      14. A CoffeeMaker is also an Appliance
      15. Upcasting works with both objects and interfaces
      16. Downcasting lets you turn your appliance back into a coffee maker
        1. When downcasting fails, as returns null
      17. Upcasting and downcasting work with interfaces, too
      18. There’s more than just public and private
      19. Access modifiers change visibility
      20. Some classes should never be instantiated
      21. An abstract class is like a cross between a class and an interface
      22. Like we said, some classes should never be instantiated
        1. Solution: use an abstract class
      23. An abstract method doesn’t have a body
      24. The Deadly Diamond of Death!
        1. Avoid ambiguity!
        2. The four principles of object-oriented programming
      25. Polymorphism means that one object can take many different forms
        1. Keep your eyes open for polymorphism in the next exercise!
    4. 8. Enums and Collections: Storing Lots of Data
      1. Strings don’t always work for storing categories of data
      2. Enums let you work with a set of valid values
      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 are hard to work with
      6. Lists make it easy to store collections of...anything
      7. Lists are more flexible than arrays
      8. Lists shrink and grow dynamically
      9. Generics can store any type
      10. Collection initializers are similar to object initializers
      11. Let’s create a List of Ducks
        1. Here’s the initializer for your List of Ducks
      12. Lists are easy, but SORTING can be tricky
        1. You could sort a list of ducks by size...
        2. ... or by kind
        3. Lists know how to sort themselves
      13. IComparable<Duck> helps your list sort its ducks
        1. An object’s CompareTo() method compares it to another object
      14. Use IComparer to tell your List how to sort
      15. Create an instance of your comparer object
        1. Multiple IComparer implementations, multiple ways to sort your objects
      16. IComparer can do complex comparisons
      17. Overriding a ToString() method lets an object describe itself
      18. Update your foreach loops to let your Ducks and Cards print themselves
        1. Add a ToString() method to your Card object, too
      19. You can upcast an entire list using IEnumerable
        1. Combine your birds into a single list
      20. You can build your own overloaded methods
      21. Use a dictionary to store keys and values
      22. The dictionary functionality rundown
        1. Your key and value can be different types
      23. Build a program that uses a dictionary
      24. And yet MORE collection types...
        1. Generic collections are an important part of the .NET Framework
      25. A queue is FIFO—First In, First Out
      26. A stack is LIFO—Last In, First Out
    5. 9. 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. Reading and writing using two objects
      7. Data can go through more than one stream
      8. Use built-in objects to pop up standard dialog boxes
        1. ShowDialog() pops up a dialog box
      9. Dialog boxes are just another WinForms control
      10. Dialog boxes are objects, too
      11. Use the built-in File and Directory classes to work with files and directories
        1. Things you can do with File:
        2. Things you can do with Directory:
      12. Use file dialogs to open and save files (all with just a few lines of code)
      13. IDisposable makes sure your objects are disposed of properly
      14. Avoid filesystem errors with using statements
        1. Use multiple using statements for multiple objects
      15. Trouble at work
        1. You can help Brian out by building a program to manage his excuses
      16. Writing files usually involves making a lot of decisions
      17. Use a switch statement to choose the right option
      18. Use a switch statement to let your deck of cards read from a file or write itself out to one
      19. Add an overloaded Deck() constructor that reads a deck of cards in from a file
      20. What happens to an object when it’s serialized?
      21. But what exactly IS an object’s state? What needs to be saved?
      22. When an object is serialized, all of the objects it refers to get serialized, too...
      23. Serialization lets you read or write a whole object graph all at once
        1. You’ll need a BinaryFormatter object
        2. Now just create a stream and read or write your objects
      24. If you want your class to be serializable, mark it with the [Serializable] attribute
      25. Let’s serialize and deserialize a deck of cards
      26. .NET uses Unicode to store characters and text
      27. C# can use byte arrays to move data around
      28. Use a BinaryWriter to write binary data
        1. Use BinaryReader to read the data back in
      29. You can read and write serialized files manually, too
      30. Find where the files differ, and use that information to alter them
      31. Working with binary files can be tricky
      32. Use file streams to build a hex dumper
        1. How to make a hex dump
        2. Working with hex
      33. StreamReader and StreamWriter will do just fine (for now)
      34. Use Stream.Read() to read bytes from a stream
  14. II. C# Lab: The Quest
    1. 10. Designing Windows Store Apps with Xaml: Taking your apps to the next level
      1. Brian’s running Windows 8
      2. Windows Forms use an object graph set up by the IDE
      3. Use the IDE to explore the object graph
      4. Windows Store apps use XAML to create UI objects
      5. Redesign the Go Fish! form as a Windows Store app page
      6. Page layout starts with controls
      7. Rows and columns can resize to match the page size
      8. Use the grid system to lay out app pages
      9. Data binding connects your XAML pages to your classes
        1. Context, path, and binding
        2. Two-way binding can get or set the source property
        3. Bind to collections with ObservableCollection
        4. Use code for binding (without using any XAML at all!)
      10. XAML controls can contain text...and more
      11. Use data binding to build Sloppy Joe a better menu
      12. Use static resources to declare your objects in XAML
      13. Use a data template to display objects
      14. INotifyPropertyChanged lets bound objects send updates
      15. Modify MenuMaker to notify you when the GeneratedDate property changes
    2. 11. Async, Await, and Data Contract Serialization: Pardon the interruption
      1. Brian runs into file trouble
      2. Windows Store apps use await to be more responsive
      3. Use the FileIO class to read and write files
        1. Use the file pickers to locate file paths
      4. Build a slightly less simple text editor
      5. A data contract is an abstract definition of your object’s data
        1. Data contract serialization uses XML files
      6. Use async methods to find and open files
      7. KnownFolders helps you access high-profile folders
      8. The whole object graph is serialized to XML
      9. Stream some Guy objects to your app’s local folder
      10. Take your Guy Serializer for a test drive
      11. Use a Task to call one async method from another
      12. Build Brian a new Excuse Manager app
      13. Separate the page, excuse, and Excuse Manager
      14. Create the main page for the Excuse Manager
      15. Add the app bar to the main page
      16. Build the ExcuseManager class
      17. Add the code-behind for the page
    3. 12. Exception Handling: Putting out fires gets old
      1. Brian needs his excuses to be mobile
        1. But the program isn’t working!
        2. When your program throws an exception, .NET generates an Exception object.
      2. Brian’s code did something unexpected
      3. All exception objects inherit from Exception
      4. The debugger helps you track down and prevent exceptions in your code
      5. Use the IDE’s debugger to ferret out exactly what went wrong in the Excuse Manager
      6. Uh oh—the code’s still got problems...
      7. Handle exceptions with try and catch
      8. What happens when a method you want to call is risky?
      9. Use the debugger to follow the try/catch flow
      10. If you have code that ALWAYS should run, use a finally block
      11. Use the Exception object to get information about the problem
      12. Use more than one catch block to handle multiple types of exceptions
      13. One class throws an exception that a method in another class can catch
      14. Bees need an OutOfHoney exception
      15. An easy way to avoid a lot of problems: using gives you try and finally for free
      16. Exception avoidance: implement IDisposable to do your own cleanup
      17. The worst catch block EVER: catch-all plus comments
        1. You should handle your exceptions, not bury them
      18. Temporary solutions are OK (temporarily)
      19. A few simple ideas for exception handling
      20. Brian finally gets his vacation...
        1. ...and things are looking up back home!
    4. 13. Captain Amazing The Death of the Object
      1. Your last chance to DO something...your object’s finalizer
      2. When EXACTLY does a finalizer run?
        1. You can SUGGEST to .NET that it’s time to collect the garbage
      3. Dispose() works with using; finalizers work with garbage collection
      4. Finalizers can’t depend on stability
      5. Make an object serialize itself in its Dispose()
      6. A struct looks like an object...
      7. ...but isn’t an object
      8. Values get copied; references get assigned
      9. Structs are value types; objects are reference types
        1. Here’s what happened...
      10. The stack vs. the heap: more on memory
      11. Use out parameters to make a method return more than one value
      12. Pass by reference using the ref modifier
      13. Use optional parameters to set default values
      14. Use nullable types when you need nonexistent values
      15. Nullable types help you make your programs more robust
      16. “Captain” Amazing...not so much
      17. Extension methods add new behavior to EXISTING classes
      18. Extending a fundamental type: string
    5. 14. Querying Data and Building Apps with LINQ: Get Control of your Data
      1. Jimmy’s a Captain Amazing super-fan...
      2. ...but his collection’s all over the place
      3. LINQ can pull data from multiple sources
      4. .NET collections are already set up for LINQ
      5. LINQ makes queries easy
      6. LINQ is simple, but your queries don’t have to be
      7. Jimmy could use some help
        1. Windows Store apps use page-based navigation
        2. Use the IDE to explore app page navigation
      8. Start building Jimmy an app
      9. Use the new keyword to create anonymous types
      10. LINQ is versatile
      11. Add the new queries to Jimmy’s app
      12. LINQ can combine your results into groups
      13. Combine Jimmy’s values into groups
      14. Use join to combine two collections into one sequence
      15. Jimmy saved a bunch of dough
      16. Use semantic zoom to navigate your data
      17. Add semantic zoom to Jimmy’s app
      18. You made Jimmy’s day
      19. The IDE’s Split App template helps you build apps for navigating data
    6. 15. Events and Delegates: What your Code does When You’re Not Looking
      1. Ever wish your objects could think for themselves?
      2. But how does an object KNOW to respond?
      3. When an EVENT occurs...objects listen
        1. Want to DO SOMETHING with an event? You need an event handler
      4. One object raises its event, others listen for it...
      5. Then, the other objects handle the event
      6. Connecting the dots
        1. Use a standard name when you add a method to raise an event
      7. The IDE generates event handlers for you automatically
      8. Generic EventHandlers let you define your own event types
        1. C# does implicit conversion when you leave out the new keyword and type
      9. Windows Forms use many different events
      10. One event, multiple handlers
      11. Windows Store apps use events for process lifetime management
        1. Use the IDE to explore process lifetime management events
      12. Add process lifetime management to Jimmy’s comics
      13. XAML controls use routed events
        1. IsHitTestVisible determines if an element is “visible” to the pointer or mouse
      14. Create an app to explore routed events
      15. Connecting event senders with event listeners
        1. “My people will get in touch with your people.”
      16. A delegate STANDS IN for an actual method
        1. A delegate adds a new type to your project
      17. Delegates in action
      18. An object can subscribe to an event...
        1. ...but that’s not always a good thing!
      19. Use a callback to control who’s listening
      20. A callback is just a way to use delegates
      21. You can use callbacks with MessageDialog commands
      22. Use delegates to use the Windows settings charm
    7. 16. Architecting Apps with the Mvvm Pattern: Great apps on the inside and outside
      1. The Head First Basketball Conference needs an app
      2. But can they agree on how to build it?
      3. Do you design for binding or for working with data?
      4. MVVM lets you design for binding and data
      5. Use the MVVM pattern to start building the basketball roster app
      6. User controls let you create your own controls
      7. The ref needs a stopwatch
      8. MVVM means thinking about the state of the app
      9. Start building the stopwatch app’s Model
      10. Events alert the rest of the app to state changes
      11. Build the view for a simple stopwatch
      12. Add the stopwatch ViewModel
      13. Finish the stopwatch app
      14. Converters automatically convert values for binding
      15. Converters can work with many different types
      16. A style alters the appearance of a type of control
        1. Styles can alter every control of a specific type
      17. Visual states make controls respond to changes
      18. Use DoubleAnimation to animate double values
      19. Use object animations to animate object values
      20. Build an analog stopwatch using the same ViewModel
      21. UI controls can be instantiated with C# code, too
      22. C# can build “real” animations, too
        1. Create a project and add the pictures
      23. Create a user control to animate a picture
      24. Make your bees fly around a page
      25. Use ItemsPanelTemplate to bind controls to a Canvas
      26. Congratulations! (But you’re not done yet...)
  15. III. C# Lab: Invaders
    1. 17. Bonus Project!: Build a Windows Phone app
      1. Bee Attack!
      2. Before you begin...
  16. A. Leftovers: The top things we wanted to include in this book
    1. #1. There’s so much more to Windows Store
    2. #2. The Basics
      1. ...more basics...
    3. #3. Namespaces and assemblies
      1. what did I just do?
      2. Building a “Hello World” program from the command line
    4. #4. Use BackgroundWorker to make your WinForms responsive
    5. #5. The Type class and GetType()
    6. #6. Equality, IEquatable, and Equals()
    7. #7. Using yield return to create enumerable objects
    8. #8. Refactoring
      1. Extract a method
      2. Rename a variable
      3. Consolidate a conditional expression
    9. #9. Anonymous types, anonymous methods, and lambda expressions
    10. #10. LINQ to XML
      1. Save and load XML files
      2. Query your data
      3. Read data from an RSS feed
    11. #11. Windows Presentation Foundation
      1. Don’t have Windows 8? Don’t worry! You can still do most of the projects in WPF.
    12. Did you know that C# and the .NET Framework can...
  17. Index
  18. About the Authors
  19. Copyright