Log In
Or create an account ->
Imperial Library
Home
About
News
Upload
Forum
Help
Login/SignUp
Index
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?
Who should probably back away from this book?
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
Read me
What version of Windows are you using?
Using Windows 8 or later? Then you’ll start with Windows Store apps
Don’t have Windows 8 or VS2013 yet? No problem—you’ll start with WPF apps
You’ll move on to create desktop applications
The technical review team
Acknowledgments
Safari® Books Online
1. Start Building with C#: Build something cool, fast!
Why you should learn C#
Here’s what the IDE automates for you...
What you get with Visual Studio and C#...
C# and the Visual Studio IDE make lots of things easy
What you do in Visual Studio...
What Visual Studio does for you...
Aliens attack!
Only you can help save the Earth
Here’s what you’re going to build
Start with a blank application
Set up the grid for your page
Add controls to your grid
Use properties to change how the controls look
Controls make the game work
You’ve set the stage for the game
What you’ll do next
Add a method that does something
Use the IDE to create your own method
Fill in the code for your method
Finish the method and run your program
Here’s what you’ve done so far
Add timers to manage the gameplay
Make the Start button work
Run the program to see your progress
Add code to make your controls interact with the player
Dragging humans onto enemies ends the game
Your game is now playable
Make your enemies look like aliens
Add a splash screen and a tile
Publish your app
Use the Remote Debugger to sideload your app
Start remote debugging
2. It’s all Just Code: Under the hood
When you’re doing this...
...the IDE does this
Where programs come from
Every program starts out as source code files
Build the program to create an executable
The .NET Framework gives you the right tools for the job
Your program runs inside the Common Language Runtime
The IDE helps you code
Anatomy of a program
Let’s take a closer look at your code
Two classes can be in the same namespace
Your programs use variables to work with data
Declare your variables
Variables vary
You have to assign values to variables before you use them
A few useful types
C# uses familiar math symbols
Use the debugger to see your variables change
Loops perform an action over and over
Use a code snippet to write simple for loops
if/else statements make decisions
Build an app from the ground up
Make each button do something
Set up conditions and see if they’re true
Use logical operators to check conditions
Windows Desktop apps are easy to build
Rebuild your app for Windows Desktop
Your desktop app knows where to start
You can change your program’s entry point
So what happened?
When you change things in the IDE, you’re also changing your code
Wait, wait! What did that say?
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
Some methods have a return value
Use what you’ve learned to build a program that uses a class
So what did you just build?
Mike gets an idea
He could create three different Navigator classes...
Mike can use objects to solve his problem
You use a class to build an object
An object gets its methods from its class
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!
Theory and practice
A little advice for the code exercises
An instance uses fields to keep track of things
Methods are what an object does. Fields are what the object knows.
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
Let’s build a class diagram
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
A few ideas for designing intuitive classes
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
So what happened?
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
Debug the mileage calculator
Combining = with an operator
Objects use variables, too
Using an int
Using an object
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
Use each element in an array like it is a normal variable
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
Controls are objects, just like any other object
I. C# Lab: A Day at the Races
5. Encapsulation: Keep your privates... Private
Kathleen is an event planner
What does the estimator do?
You’re going to build a program for Kathleen
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 makes your classes...
Mike’s navigator program could use better encapsulation
Think of an object as a black box
A few ideas for encapsulating classes
Encapsulation keeps your data pristine
A quick example of encapsulation
Properties make encapsulation easier
Build an application to test the Farmer class
Use automatic properties to finish the class
Fully encapsulate the Farmer 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
Here’s what we’re going to do:
Build the Part y 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
Dinner parties and birthday parties are both parties
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 what you need to override
Think about how to group the animals
Create the class hierarchy
Every subclass extends its base class
C# always calls the most specific method
Use a colon to inherit from a base class
We know that inheritance adds the base class fields, properties, and methods to the subclass...
...but some birds don’t fly!
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
Hiding methods versus overriding methods
Use different references to call hidden methods
Use the new keyword when you’re hiding methods
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
The base class constructor is executed before the subclass constructor
Now you’re ready to finish the job for Kathleen!
Build a beehive management system
How you’ll build the beehive management 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
Lots of things are still the same
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
Any class that implements an interface that inherits from IWorker must implement its methods and properties
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
When downcasting fails, as returns null
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
Solution: use an abstract class
An abstract method doesn’t have a body
The four principles of object-oriented programming
Polymorphism means that one object can take many different forms
Keep your eyes open for polymorphism in the next exercise!
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...
...but what if you wanted to do more?
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 are similar to object initializers
Let’s create a List of Ducks
Here’s the initializer for your List of Ducks
Lists are easy, but SORTING can be tricky
Lists know how to sort themselves
IComparable<Duck> helps your list sort its ducks
An object’s CompareTo() method compares it to another object
Use IComparer to tell your List how to sort
Create an instance of your comparer object
Multiple IComparer implementations, multiple ways to sort your objects
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
Add a ToString() method to your Card object, too
You can upcast an entire list using IEnumerable
Combine your birds into a single list
You can build your own overloaded methods
Use a dictionary to store keys and values
The dictionary functionality rundown
Your key and value can be different types
Build a program that uses a dictionary
And yet MORE collection types...
Generic collections are an important part of the .NET Framework
A queue is FIFO—First In, First Out
A stack is LIFO—Last In, First Out
9. 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
Things you can do with a stream:
A FileStream reads and writes bytes to a file
Write text to a file in three 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
ShowDialog() pops up a dialog box
Dialog boxes are just another WinForms control
Dialog boxes are objects, too
Use the built-in File and Directory classes to work with files and directories
Things you can do with File:
Things you can do with Directory:
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 filesystem errors with using statements
Use multiple using statements for multiple objects
Trouble at work
You can help Brian out by building a program to manage his excuses
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 graph all at once
You’ll need a BinaryFormatter object
Now just create a stream and read or write your objects
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
Use BinaryReader to read the data back in
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
How to make a hex dump
Working with hex
StreamReader and StreamWriter will do just fine (for now)
Use Stream.Read() to read bytes from a stream
II. C# Lab: The Quest
10. Designing Windows Store Apps with XAML: Taking your apps to the next level
Brian’s running Windows 8
Windows Forms use an object graph set up by the IDE
Use the IDE to explore the object graph
Windows Store apps use XAML to create UI objects
Redesign the Go Fish! form as a Windows Store app page
Page layout starts with controls
Rows and columns can resize to match the page size
Use the grid system to lay out app pages
Data binding connects your XAML pages to your classes
Context, path, and binding
Two-way binding can get or set the source property
Bind to collections with ObservableCollection
Use code for binding (without using any XAML at all!)
XAML controls can contain text...and more
Use data binding to build Sloppy Joe a better menu
Use static resources to declare your objects in XAML
Use a data template to display objects
INotifyPropertyChanged lets bound objects send updates
Modify MenuMaker to notify you when the GeneratedDate property changes
11. Async, Await, and Data Contract Serialization: Pardon the interruption
Brian runs into file trouble
Windows Store apps use await to be more responsive
Use the FileIO class to read and write files
Use the file pickers to locate file paths
Build a slightly less simple text editor
A data contract is an abstract definition of your object’s data
Data contract serialization uses XML files
Use async methods to find and open files
KnownFolders helps you access high-profile folders
The whole object graph is serialized to XML
Stream some Guy objects to XML files
Take your Guy Serializer for a test drive
Use a Task to call one async method from another
Build Brian a new Excuse Manager app
Separate the page, excuse, and Excuse Manager
Create the main page for the Excuse Manager
Add the app bar to the main page
Build the ExcuseManager class
Add the code-behind for the page
12. Exception Handling: Putting out fires gets old
Brian needs his excuses to be mobile
But the program isn’t working!
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 that a method in another class can catch
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
You should handle your exceptions, not bury them
Temporary solutions are OK (temporarily)
A few simple ideas for exception handling
Brian finally gets his vacation...
...and things are looking up back home!
13. Captain Amazing: The Death of the Object
Your last chance to DO something... your object’s finalizer
When EXACTLY does a finalizer run?
You can SUGGEST to .NET that it’s time to collect the garbage
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
Here’s what happened...
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
14. Querying Data and Building Apps With Linq: Get control of your data
Jimmy’s a Captain Amazing super-fan...
...but his collection’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
Jimmy could use some help
Windows Store apps use page-based navigation
Use the IDE to explore app page navigation
Start building Jimmy an app
Use the new keyword to create anonymous types
LINQ is versatile
Add the new queries to Jimmy’s app
LINQ can combine your results into groups
Combine Jimmy’s values into groups
Use join to combine two collections into one sequence
Jimmy saved a bunch of dough
Use semantic zoom to navigate your data
Add semantic zoom to Jimmy’s app
You made Jimmy’s day
The IDE’s Split App template helps you build apps for navigating data
15. 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
Want to DO SOMETHING with an event? You need an event handler
One object raises its event, others listen for it...
Then, the other objects handle the event
Connecting the dots
Use a standard name when you add a method to raise an event
The IDE generates event handlers for you automatically
Generic EventHandlers let you define your own event types
C# does implicit conversion when you leave out the new keyword and type
Windows Forms use many different events
One event, multiple handlers
Windows Store apps use events for process lifetime management
Use the IDE to explore process lifetime management events
Add process lifetime management to Jimmy’s comics
XAML controls use routed events
IsHitTestVisible determines if an element is “visible” to the pointer or mouse
Create an app to explore routed events
Connecting event senders with event listeners
“My people will get in touch with your people.”
A delegate STANDS IN for an actual method
A delegate adds a new type to your project
Delegates in action
An object can subscribe to an event...
...but that’s not always a good thing!
Use a callback to control who’s listening
A callback is just a way to use delegates
MessageDialog uses the callback pattern
Use delegates to use the Windows settings charm
16. Architecting Apps with the mvvm Pattern: Great apps on the inside and outside
The Head First Basketball Conference needs an app
But can they agree on how to build it?
Do you design for binding or for working with data?
MVVM lets you design for binding and data
Use the MVVM pattern to start building the basketball roster app
User controls let you create your own controls
The ref needs a stopwatch
MVVM means thinking about the state of the app
Start building the stopwatch app’s Model
Events alert the rest of the app to state changes
Build the view for a simple stopwatch
Add the stopwatch ViewModel
Finish the stopwatch app
Converters automatically convert values for binding
Converters can work with many different types
Styles set properties on multiple controls
Use a resource dictionary to share resources between pages
Visual states make controls respond to changes
Use DoubleAnimation to animate double values
Use object animations to animate object values
Build an analog stopwatch using the same ViewModel
UI controls can be instantiated with C# code, too
C# can build “real” animations, too
Create a project and add the pictures
Create a user control to animate a picture
Make your bees fly around a page
Use ItemsPanelTemplate to bind controls to a Canvas
Congratulations! (But you’re not done yet...)
III. C# Lab Invaders
A. Leftovers: The top 10 things we wanted to include in this book
#1. There’s so much more to Windows Store
#2. The Basics
...more basics...
#3. Namespaces and assemblies
...so what did I just do?
Building a “Hello World” program from the command line
#4. Use BackgroundWorker to make your WinForms responsive
#5. The Type class and GetType()
#6. Equality, IEquatable, and Equals()
#7. Using yield return to create enumerable objects
#8. Refactoring
Extract a method
Rename a variable
Consolidate a conditional expression
#9. Anonymous types, anonymous methods, and lambda expressions
#10. LINQ to XML
Save and load XML files
Query your data
Read data from an RSS feed
Did you know that C# and the .NET Framework can...
B. Windows Presentation Foundation: WPF Learner’s Guide to Head First C#
Why you should learn WPF
Build WPF projects in Visual Studio
How to use this appendix
Chapter 1
Start with a blank application
Set up the grid for your window
Add controls to your grid
Use properties to change how the controls look
Controls make the game work
You’ve set the stage for the game
What you’ll do next
Add a method that does something
Use the IDE to create your own method
Fill in the code for your method
Finish the method and run your program
Here’s what you’ve done so far
Add timers to manage the gameplay
Make the Start button work
Run the program to see your progress
Add code to make your controls interact with the player
Dragging humans onto enemies ends the game
Your game is now playable
Make your enemies look like aliens
Chapter 2
Use the debugger to see your variables change
Build an app from the ground up
Chapter 10
WPF applications use XAML to create UI objects
Redesign the Go Fish! form as a WPF application
Page layout starts with controls
Rows and columns can resize to match the page size
Use data binding to build Sloppy Joe a better menu
Use static resources to declare your objects in XAML
Use a data template to display objects
INotifyPropertyChanged lets bound objects send updates
Modify MenuMaker to notify you when the GeneratedDate property changes
Chapter 11
C# programs can use await to be more responsive
Stream some Guy objects to a file
Take your Guy Serializer for a test drive
Chapter 12
Brian’s code did something unexpected
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 should ALWAYS run, use a finally block
Chapter 14
Build a WPF comic query application
Chapter 15
XAML controls use routed events
IsHitTestVisible determines if an element is “visible” to the pointer or mouse
Create an app to explore routed events
Chapter 16
Use the MVVM pattern to start building the basketball roster app
User controls let you create your own controls
Build the view for a simple stopwatch
Finish the stopwatch app
Converters automatically convert values for binding
Converters can work with many different types
Build an analog stopwatch using the same ViewModel
UI controls can be instantiated with C# code, too
Create a user control to animate a picture
Make your bees fly around a page
Use ItemsPanelTemplate to bind controls to a Canvas
Congratulations! (But you’re not done yet...)
Index
About the Authors
Copyright
← Prev
Back
Next →
← Prev
Back
Next →