Book description
You want to learn C# programming, but you're not sure you want to suffer through another tedious technical book. You're in luck: Head First C# introduces this language in a fun, visual way. You'll quickly learn everything from creating your first program to learning sophisticated coding skills with C# 4.0, Visual Studio 2010 and .NET 4, while avoiding common errors that frustrate many students.
The second edition offers several hands-on labs along the way to help you build and test programs using skills you've learned up to that point. In the final lab, you'll put everything together. From objects to garbage collection and from exceptions to interactions, you'll learn C# in a way that engages and entertains your brain. Here are a few of the topics you'll learn:
- Start by building a useful application with pre-built components in Visual Studio 2010
- Discover how objects work, using real-world examples
- Store numbers, text, and other basic data types using primitives
- Save complex data in files and databases with great C# tools
- Build intuitive and easy-to-use interfaces by following simple rules
- Design your code to catch exceptions -- things you don't expect
- Develop good programming habits, such as refactoring code and applying unit tests
- Learn how web services put your programs in touch with the rest of the world
- Make it easy for other people to install your software
Publisher resources
Table of contents
- Head First C#
- Dedication
- A Note Regarding Supplemental Files
- Advance Praise for Head First C#
- Praise for other Head First books
-
How to Use this Book: Intro
- Who is this book for?
- We know what you’re thinking
- And we know what your brain is thinking
- Metacognition: thinking about thinking
- Here’s what WE did
- Here’s what YOU can do to bend your brain into submission
- What you need for this book
- Read me
- The technical review team
- Acknowledgments
- Safari® Books Online
-
1. Get Productive with C#: Visual Applications, in 10 minutes or less
- Why you should learn C#
- C# and the Visual Studio IDE make lots of things easy
- Help the CEO go paperless
- Get to know your users’ needs before you start building your program
- Here’s what you’re going to build
- What you do in Visual Studio...
- What Visual Studio does for you...
- Develop the user interface
- Visual Studio, behind the scenes
- Add to the auto-generated code
- You can already run your application
- Where are my files?
- Here’s what we’ve done so far
- We need a database to store our information
- The IDE created a database
- SQL is its own language
- Creating the table for the Contact List
- The blanks on the contact card are columns in our People table
- Finish building the table
- Insert your card data into the database
- Connect your form to your database objects with a data source
- Add database-driven controls to your form
- Good programs are intuitive to use
- Test drive
- How to turn YOUR application into EVERYONE’S application
- Give your users the application
- You’re NOT done: test your installation
- You’ve built a complete data-driven application
-
2. It’s All Just Code: Under the hood
- When you’re doing this...
- ...the IDE does this
- Where programs come from
- The IDE helps you code
- When you change things in the IDE, you’re also changing your code
- Anatomy of a program
- Your program knows where to start
- You can change your program’s entry point
- Two classes can be in the same namespace
- Your programs use variables to work with data
- C# uses familiar math symbols
- Use the debugger to see your variables change
- Loops perform an action over and over
- Time to start coding
- if/else statements make decisions
- Set up conditions and see if they’re true
-
3. Objects: Get Oriented!: Making code make sense
- How Mike thinks about his problems
- How Mike’s car navigation system thinks about his problems
- Mike’s Navigator class has methods to set and modify routes
- Use what you’ve learned to build a program that uses a class
- Mike gets an idea
- Mike can use objects to solve his 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...brought to you by objects!
- An instance uses fields to keep track of things
- Let’s create some instances!
- Thanks for the memory
- What’s on your program’s mind
- You can use class and method names to make your code intuitive
- Give your classes a natural structure
- Class diagrams help you organize your classes so they make sense
- Build a class to work with some guys
- Create a project for your guys
- Build a form to interact with the guys
- There’s an easier way to initialize objects
-
4. Types and References: It’s 10:00. Do you know where your data is?
- The variable’s type determines what kind of data it can store
- A variable is like a data to-go cup
- 10 pounds of data in a 5 pound bag
- Even when a number is the right size, you can’t just assign it to any variable
- When you cast a value that’s too big, C# will adjust it automatically
- C# does some casting automatically
- When you call a method, the arguments must be compatible with the types of the parameters
- Combining = with an operator
- Objects use variables, too
- Refer to your objects with reference variables
- References are like labels for your object
- If there aren’t any more references, your object gets garbage-collected
- Multiple references and their side effects
- Two references means TWO ways to change an object’s data
- A special case: arrays
- Arrays can contain a bunch of reference variables, too
- Welcome to Sloppy Joe’s Budget House o’ Discount Sandwiches!
- Objects use references to talk to each other
- Where no object has gone before
- Build a typing game
-
I. C# Lab: A Day at the Races
-
5. Encapsulation: Keep your privates... private
- Kathleen is an event planner
- What does the estimator do?
- Kathleen’s Test Drive
- Each option should be calculated individually
- 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 inside the class
- Encapsulation keeps your data pristine
- Properties make encapsulation easier
- Build an application to test the Farmer class
- Use automatic properties to finish the class
- What if we want to change the feed multiplier?
- Use a constructor to initialize private fields
-
6. Inheritance: Your object’s family tree
- Kathleen does birthday parties, too
- We need a BirthdayParty class
- Build the Party Planner version 2.0
- One more thing...can you add a $100 fee for parties over 12?
- 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?
- Use inheritance to avoid duplicate code in subclasses
- Different animals make different noises
- Think about how to group the animals
- Create the class hierarchy
- Every subclass extends its base class
- Use a colon to inherit from 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 methods it inherited
- Any place where you can use a base class, you can use one of its subclasses instead
- A subclass can hide methods in the superclass
- 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 one, too
- Now you’re ready to finish the job for Kathleen!
- Build a beehive management system
- First you’ll build the basic system
- Use inheritance to extend the bee management system
-
7. Interfaces and Abstract Classes: Making classes keep their promises
- Let’s get back to bee-sics
- We can use inheritance to create classes for different types of bees
- An interface tells a class that it must implement certain methods and properties
- Use the interface keyword to define an interface
- Now you can create an instance of NectarStinger that does both jobs
- Classes that implement interfaces have to include ALL of the interface’s methods
- Get a little practice using interfaces
- You can’t instantiate an interface, but you can reference an interface
- Interface references work just like object references
- You can find out if a class implements a certain interface with “is”
- Interfaces can inherit from other interfaces
- The RoboBee 4000 can do a worker bee’s job without using valuable honey
- is tells you what an object implements, as tells the compiler how to treat your object
- A CoffeeMaker is also an Appliance
- Upcasting works with both objects and interfaces
- Downcasting lets you turn your appliance back into a coffee maker
- Upcasting and downcasting work with interfaces, too
- There’s more than just public and private
- Access modifiers change visibility
- Some classes should never be instantiated
- An abstract class is like a cross between a class and an interface
- Like we said, some classes should never be instantiated
- An abstract method doesn’t have a body
- Polymorphism means that one object can take many different forms
-
8. Enums and Collections; Storing lots of 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 are hard to work with
- Lists make it easy to store collections of...anything
- Lists are more flexible than arrays
- Lists shrink and grow dynamically
- Generics can store any type
- Collection initializers work just like 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
- IComparer can do complex comparisons
- Overriding a ToString() method lets an object describe itself
- Update your foreach loops to let your Ducks and Cards print themselves
- You can upcast an entire list using IEnumerable
- You can build your own overloaded methods
- 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
-
5. Encapsulation: Keep your privates... private
-
II. C# Lab: The Quest
-
9. Reading and Writing Files: Save the byte array, save the world
- .NET uses streams to read and write data
- Different streams read and write different things
- A FileStream reads and writes bytes to a file
- How to write text to a file in 3 simple steps
- The Swindler launches another diabolical plan
- Reading and writing using two objects
- Data can go through more than one stream
- Use built-in objects to pop up standard dialog boxes
- Dialog boxes are just another .NET control
- Dialog boxes are objects, too
- Use the built-in File and Directory classes to work with files and directories
- Use file dialogs to open and save files (all with just a few lines of code)
- IDisposable makes sure your objects are disposed of properly
- Avoid file system errors with using statements
- Trouble at work
- Writing files usually involves making a lot of decisions
- Use a switch statement to choose the right option
- Use a switch statement to let your deck of cards read from a file or write itself out to one
- Add an overloaded Deck() constructor that reads a deck of cards in from a file
- 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...
- Serialization lets you read or write a whole object all at once
- If you want your class to be serializable, mark it with the [Serializable] attribute
- Let’s serialize and deserialize a deck of cards
- .NET uses Unicode to store characters and text
- C# can use byte arrays to move data around
- Use a BinaryWriter to write binary data
- You can read and write serialized files manually, too
- Find where the files differ, and use that information to alter them
- Working with binary files can be tricky
- Use file streams to build a hex dumper
- StreamReader and StreamWriter will do just fine (for now)
- Use Stream.Read() to read bytes from a stream
-
10. Exception Handling: Putting out fires gets old
- Brian needs his excuses to be mobile
- When your program throws an exception, .NET generates an Exception object
- Brian’s code did something unexpected
- All exception objects inherit from Exception
- The debugger helps you track down and prevent exceptions in your code
- Use the IDE’s debugger to ferret out exactly what went wrong in the Excuse Manager
- Uh oh—the code’s still got problems...
- Handle exceptions with try and catch
- What happens when a method you want to call is risky?
- Use the debugger to follow the try/catch flow
- If you have code that ALWAYS should run, use a finally block
- Use the Exception object to get information about the problem
- Use more than one catch block to handle multiple types of exceptions
- One class throws an exception, another class catches the exception
- Bees need an OutOfHoney exception
- An easy way to avoid a lot of problems: using gives you try and finally for free
- Exception avoidance: implement IDisposable to do your own cleanup
- The worst catch block EVER: catch-all plus comments
- Temporary solutions are OK (temporarily)
- A few simple ideas for exception handling
- Brian finally gets his vacation...
-
11. Events and Delegates: What your code does when you’re not looking
- Ever wish your objects could think for themselves?
- But how does an object KNOW to respond?
- When an EVENT occurs...objects listen
- One object raises its event, others listen for it...
- Then, the other objects handle the event
- Connecting the dots
- The IDE creates event handlers for you automatically
- Generic EventHandlers let you define your own event types
- The forms you’ve been building all use events
- One event, multiple handlers
- Connecting event senders with event receivers
- A delegate STANDS IN for an actual method
- Delegates in action
- An object can subscribe to an event...
- Use a callback to control who’s listening
- A callback is just a way to use delegates
-
12. Review and Preview: Knowledge, power, and building cool stuff
- You’ve come a long way, baby
- We’ve also become beekeepers
- The beehive simulator architecture
- Building the beehive simulator
- Life and death of a flower
- Now we need a Bee class
- P. A. H. B. (Programmers Against Homeless Bees)
- The hive runs on honey
- Filling out the Hive class
- The hive’s Go() method
- We’re ready for the World
- We’re building a turn-based system
- Here’s the code for World
- Giving the bees behavior
- The main form tells the world to Go()
- We can use World to get statistics
- Timers fire events over and over again
- The timer’s using an event handler behind the scenes
- Add a timer to the simulator
- Test drive
- Let’s work with groups of bees
- A collection collects...DATA
- LINQ makes working with data in collections and databases easy
- Test drive (Part 2)
- One final challenge: Open and Save
-
13. Controls and Graphics: Make it pretty
- You’ve been using controls all along to interact with your programs
- Form controls are just objects
- Use controls to animate the beehive simulator
- Add a renderer to your architecture
- The renderer draws everything in the world on the two forms
- Controls are well suited for visual display elements
- Build your first animated control
- BeeControl is LIKE a PictureBox...so let’s start by INHERITING from PictureBox
- Create a button to add the BeeControl to your form
- Your controls need to dispose their controls, too!
- A UserControl is an easy way to build a control
- Your simulator’s renderer will use your BeeControl to draw animated bees on your forms
- Add the hive and field forms to the project
- Build the renderer
- Now connect the main form to your two new forms, HiveForm and FieldForm
- Test drive...ahem...buzz
- Looks great, but something’s not quite right...
- Let’s take a closer look at those performance issues
- You resized your Bitmaps using a Graphics object
- Your image resources are stored in Bitmap objects
- Use System.Drawing to TAKE CONTROL of graphics yourself
- A 30-second tour of GDI+ graphics
- Use graphics to draw a picture on a form
- Graphics can fix our transparency problem...
- Use the Paint event to make your graphics stick
- A closer look at how forms and controls repaint themselves
- Double buffering makes animation look a lot smoother
- Double buffering is built into forms and controls
- Use a Graphics object and an event handler for printing
- PrintDocument works with the print dialog and print preview window objects
-
14. Captain Amazing: The Death of the Object
- Your last chance to DO something... your object’s finalizer
- When EXACTLY does a finalizer run?
- Dispose() works with using, finalizers work with garbage collection
- Finalizers can’t depend on stability
- Make an object serialize itself in its Dispose()
- A struct looks like an object...
- ...but isn’t 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
- Use nullable types when you need nonexistent values
- Nullable types help you make your programs more robust
- Captain Amazing...not so much
- Extension methods add new behavior to EXISTING classes
- Extending a fundamental type: string
-
15. LINQ: Get control of your data
- An easy project...
- ...but the data’s all over the place
- LINQ can pull data from multiple sources
- .NET collections are already set up for LINQ
- LINQ makes queries easy
- LINQ is simple, but your queries don’t have to be
- LINQ is versatile
- LINQ can combine your results into groups
- Combine Jimmy’s values into groups
- Use join to combine two collections into one query
- Jimmy saved a bunch of dough
- Connect LINQ to a SQL database
- Use a join query to connect Starbuzz and Objectville
-
9. Reading and Writing Files: Save the byte array, save the world
-
III. C# Lab: Invaders
-
A. Leftovers: The top 11 things we wanted to include in this book
- #1. The Basics
- #2. Namespaces and assemblies
- #3. Use BackgroundWorker to make your UI responsive
- #4. The Type class and GetType()
- #5. Equality, IEquatable, and Equals()
- #6. Using yield return to create enumerable objects
- #7. Refactoring
- #8. Anonymous types, anonymous methods, and lambda expressions
- #9. Serializing data using DataContractSerializer
- #10. LINQ to XML
- #11. Windows Presentation Foundation
- Did you know that C# and the .NET Framework can...
-
A. Leftovers: The top 11 things we wanted to include in this book
- Index
- About the Authors
- Copyright
Product information
- Title: Head First C#, 2nd Edition
- Author(s):
- Release date: May 2010
- Publisher(s): O'Reilly Media, Inc.
- ISBN: 9781449380342
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
Head First C#, 5th Edition
What will you learn from this book? Go from beginner to confident developer as you create …
book
Head First C#, 3rd Edition
Head First C# is a complete learning experience for learning how to program with C#, XAML, …
book
Head First C
Ever wished you could learn C from a book? Head First C provides a complete learning …