Log In
Or create an account ->
Imperial Library
Home
About
News
Upload
Forum
Help
Login/SignUp
Index
1. Start Building with c#: Build Something Great... Fast!
Why you should learn C#
Visual Studio is your gateway to C#
Visual Studio is a tool for writing code and exploring C#
Create your first project in Visual Studio
Let’s build a game!
Your animal match game is a WPF app
Here’s how you’ll build your game
Create a WPF project in Visual Studio
Visual Studio created a project folder full of files for you
Use XAML to design your window
Design the window for your game
Set the window size and title with XAML properties
Add rows and columns to the XAML grid
Make the rows and columns equal size
Add a TextBlock control to your Grid
Now you’re ready to start writing code for your game
Generate a method to set up the game
Finish your SetUpGame method
Run your program
Add your new project to source control
The next step to build the game is handling mouse clicks
Make your TextBlocks respond to mouse clicks
Add the TextBlock_MouseDown code
Make the rest of the TextBlocks call the same MouseDown event handler
Finish the game by adding a timer
Add a timer to your game’s code
Use the debugger to troubleshoot the exception
Add the rest of the code and finish the game
Update your code in source control
Even better if’s...
I. Unity Lab 1: Start Exploring Unity
2. Dive Into C#: Statements, Classes, and Code
Let’s take a closer look at the files for a console app
A statement performs one single action
Two classes can be in the same namespace (and file!)
The IDE helps you build your code right.
Statements are the building blocks for your apps
Your programs use variables to work with data
Declare your variables
Variables vary
You need to assign values to variables before you use them
A few useful types
Generate a new method to work with variables
Add code that uses operators to your method
Use the debugger to watch your variables change
Use operators to work with variables
if statements make decisions
if/else statements also do something if a condition isn’t true
Loops perform an action over and over
while loops keep looping statements while a condition is true
do/while loops run the statements then check the condition
for loops run a statement after each loop
Use code snippets help to write loops
Some useful things to keep in mind about C# code
Controls drive the mechanics of your user interfaces
Create a WPF app to experiment with controls
Add a TextBox control to your app
Add C# code to update the TextBlock
Add an event handler that only allows number input
Add sliders to the bottom row of the grid
Add C# code to make the rest of the controls work
II. Unity Lab 2: Write C# Code for Unity
3. Objects... Get Oriented! Making code make sense
If code is useful, it gets reused
Some methods return a value
Let’s build a program that picks some cards
string[] cards = PickSomeCards(5);
Create your PickRandomCards console app
Finish your PickSomeCards method
Your finished CardPicker class
Ana’s working on her next game
Ana’s game is evolving...
... so how can Ana make things easier for herself?
Build a simple paper prototype for a classic game
Up next: build a WPF version of your card picking app
A StackPanel is a container that stacks other controls
Reuse your CardPicker class in a new WPF app
Use a Grid and StackPanel to lay out the main window
Lay out your Card Picker desktop app’s window
Ana’s prototypes look great...
Ana can use objects to solve her 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 for Ana... brought to you by objects
Theory and practice
An instance uses fields to keep track of things
Methods are what an object does. Fields are what the object knows.
Thanks for the memory
What’s on your program’s mind
Sometimes code can be difficult to read
Extremely compact code can be especially problematic
Most code doesn’t come with a manual
Use intuitive class and method names
Build a class to work with some guys
There’s an easier way to initialize objects with C#
Use the C# Interactive window to run C# code
III. Unity Lab 3: GameObject Instances
4. Types and References: Getting the Reference
Ryan is looking to improve his game
Storytelling, fantasy, and mechanics
Character sheets store different types of data on paper
A variable’s type determines what kind of data it can store
C# has several types for whole numbers
Types for storing really HUGE and really tiny numbers
Let’s talk about strings
A literal is a value written directly into your code
Use suffixes to give your literals types
A variable is like a data to-go cup
Use the Convert class to explore bits and bytes
Other types come in different sizes, too
10 pounds of data in a 5-pound bag
Casting lets you copy values that C# can’t automatically convert to another type
So what happened?
When you cast a value that’s too big, C# adjusts it to fit its new container
C# does some conversion automatically
When you call a method, the arguments need to be compatible with the types of the parameters
Ryan is constantly improving his game
Let’s help Ryan experiment with ability scores
And now we can finally fix Ryan’s bug
Use reference variables to access your objects
References are like sticky notes for your objects
If there aren’t any more references, your object gets garbage-collected
Multiple references and their side effects
Two references mean TWO variables that can change the same object’s data
Objects use references to talk to each other
Arrays hold multiple values
Use each element in an array like it’s a normal variable
Arrays can contain reference variables
null means a reference points to nothing
A Random Test Drive
Welcome to Sloppy Joe’s Budget House o’ Discount Sandwiches!
IV. Unity Lab 4: User Interfaces
5. Encapsulation: Keep your privates... private
Let’s help Ryan roll for damage
Create a console app to calculate damage
Design the XAML for a WPF version of the damage calculator
The code-behind for the WPF damage calculator
Tabletop talk (or maybe... dice discussion?)
Let’s try to fix that bug
Use Debug.WriteLine to print diagnostic information
It’s easy to accidentally misuse your objects
Encapsulation means keeping some of the data in a class private
Use encapsulation to control access to your class’s methods and fields
But is the RealName field REALLY protected?
Private fields and methods can only be accessed from instances of the same class
Think of an object as a black box
Encapsulation makes your classes...
A few ideas for encapsulating classes
Let’s use encapsulation to improve the SwordDamage class
Is every member of the SwordDamage class public?
Are fields or methods being misused?
Is there calculation required after setting a field?
So what fields and methods really need to be public?
Encapsulation keeps your data safe
Let’s use encapsulation in a simple class
Write a console app to test the MachineGun class
Our class is well-encapsulated, but...
Properties make encapsulation easier
Replace the GetBullets and SetBullets methods with a property
Modify your Main method to use the Bullets property
Debug your MachineGun class to understand how the property works
Auto-implemented properties simplify your code
Use the prop snippet to create an auto-implemented property
Use a private setter to create a read-only property
Make the BulletsLoaded setter private
What if we want to change the magazine size?
But there’s a problem... how do we initialize MagazineSize?
Use a constructor with parameters to initialize properties
Specify arguments when you use the new keyword
A few useful facts about methods and properties
Objectcross
Objectcross solution
V. Unity Lab 5: Raycasting
6. Inheritance Your object’s family tree
Calculate damage for MORE weapons
Use a switch statement to match several candidates
One more thing... can we calculate damage for a dagger? and a mace? and a staff? and...
When your classes use inheritance, you only need to write your code once
Build up your class model by starting general and getting more specific
How would you design a zoo simulator?
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
Any place where you can use a base class, you can use one of its subclasses instead
Use a colon to extend a base class
We know that inheritance adds the base class fields, properties, and methods to the subclass...
...but some birds don’t fly!
A subclass can override methods to change or replace members it inherited
Some members are only implemented in a subclass
Use the debugger to understand how overriding works
Build an app to explore virtual and override
A subclass can hide methods in the superclass
Hiding methods versus overriding methods
Use the new keyword when you’re hiding methods
Use different references to call hidden 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 to call it
A subclass and base class can have different constructors
It’s time to finish the job for Ryan
When your classes overlap as little as possible, that’s an important design principle called separation of concerns
Use the debugger to really understand how these classes work
Build a beehive management system
The beehive management system class model
The UI: add the XAML for the main window
The Queen class: how she manages the worker bees
Feedback drives your Beehive Management game
Workers and honey are in a feedback loop
Your game is turn-based... now let’s convert it to a real-time game
Some classes should never be instantiated
An abstract class is an intentionally incomplete class
Like we said, some classes should never be instantiated
Solution: use an abstract class
An abstract method doesn’t have a body
Abstract properties work just like abstract methods
The Deadly Diamond of Death
VI. Unity Lab 6: Scene Navigation
7. Interfaces, Casting, and “is” Making Classes keep their Promises
The beehive is under attack!
So we need a DefendHive method, because enemies can attack at any time
We can use casting to call the DefendHive method...
... but what if we add more Bee subclasses that can defend?
An interface defines methods and properties that a class must implement...
... but there’s no limit on interfaces that a class can implement
Interfaces let unrelated classes do the same job
Get a little practice using interfaces
You can’t instantiate an interface, but you can reference an interface
If you try to instantiate an interface, your code won’t build...
...but use the interface to reference an object you already have
Interface references are ordinary object references
The RoboBee 4000 can do a worker bee’s job without using valuable honey
The IWorker’s Job propert y is a hack
Use “is” to check the t ype of an object
Use the “is” keyword to access methods in a subclass
What if we want different animals to swim or hunt in packs?
Use interfaces to you work with classes that do the same job
Use the is keyword to check if the Animal is a swimmer or pack hunter
C# helps you safely navigate your class hierarchy
C# has another tool for safe type conversion: the as keyword
Use upcasting and downcasting to move up and down a class hierarchy
A CoffeeMaker is also an Appliance
Upcasting turns your CoffeeMaker into an Appliance
Downcasting turns your Appliance back into a CoffeeMaker
Upcasting and downcasting work with interfaces, too
Interfaces can inherit from other interfaces
Interfaces static members work exactly like in classes
Default implementations give bodies to interface methods
Add a ScareAdults method with a default implementation
Data binding updates WPF controls automatically
Modify the beehive management system to use data binding
Polymorphism means that one object can take many different forms
Keep your eyes open for polymorphism!
The four core principles of object-oriented programming
OOPcross
OOPcross Solution
8. Enums and Collections Organizing your data
Strings don’t always work for storing categories of data
Enums let you work with a set of valid values
An enum defines a new type
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 can be annoying to work with
Lists make it easy to store collections of… anything
Lists are more flexible than arrays
Let’s build an app to store shoes
Generic collections can store any type
Generic lists are declared using <angle brackets>
Code Magnets
Code Magnets Solution
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
Add an IComparer to your project
Create an instance of your comparer object
Multiple IComparer implementations, multiple ways to sort your objects
Comparers can do complex comparisons
Overriding a ToString method lets an object describe itself
Override the ToString method to see your Ducks in the IDE
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<T>
Use a Dictionary to store keys and values
The Dictionary functionalit y rundown
Your key and value can be different types
Build a program that uses a dictionary
And yet MORE collection t ypes…
Generic .NET collections implement IEnumerable
A queue is FIFO—First In, First Out
A stack is LIFO—Last In, First Out
Let’s build an app to work with decks of cards
Add a Deck class to hold the cards
Create a Deck that extends Obser vableCollection
Add a Window.Resources with t wo instances of the Deck class
Use Visual Studio to set up data binding
9. LINQ and Lambdas Get Control of your data
Jimmy’s a Captain Amazing super-fan...
…but his collection’s all over the place
Use LINQ to query your collections
LINQ works with any IEnumerable<T>
LINQ methods enumerate your sequences
LINQ works with objects
LINQ’s query syntax
Anatomy of a query
The var keyword lets C# figure out variable t ypes for you
When you use var, C# figures out the variable’s type automatically
LINQ magnets
LINQ Magnets Solution
LINQ is versatile
LINQ queries aren’t run until you access their results
Use a group query to separate your sequence into groups
Anatomy of a group query
Use join queries to merge data from t wo sequences
Use the new keyword to create anonymous types
Unit tests help you make sure your code works
Visual Studio for Windows has the Test Explorer window
Visual Studio for Mac has the Unit Test pad
Add a unit test project to your solutionAdd
Write your first unit test
Write a unit test for the GetReviews method
Write unit tests to handle edge cases and weird data
Use the => operator to create lambda expressions
A Lambda Test Drive
Refactor a clown with lambdas
Use the ?: operator to make your lambdas make choices
Lambda expressions and LINQ
Use lambda expressions with methods that take a Func parameter
LINQ queries can be written as chained LINQ methods
The OrderBy LINQ method sorts a sequence
The Where LINQ method pulls out a subset of a sequence
Use the => operator to create switch expressions
Explore the Enumerable class
Enumerable.Empty creates an empty sequence of any type
Enumerable.Repeat repeats a value a number of times
So what exactly is an IEnumerable<T>?
Create an enumerable sequence by hand
Use yield return to create your own sequences
Use the debugger to explore yield return
Use yield return to refactor ManualSportSequence
Add an indexer to BetterSportSequence
Collectioncross
Collectioncross solution
10. Reading and writing files Save the last byte for me!
.NET uses streams to read and write data
Different streams read and write different things
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
StreamWriter Magnets
StreamWriter Magnets Solution
Use a StreamReader to read a file
Data can go through more than one stream
Pool Puzzle
Pool Puzzle Solution
Use the File and Directory classes to work with files and directories
IDisposable makes sure objects are closed properly
Use the IDE to explore IDisposable
Avoid filesystem errors with using statements
Use multiple using statements for multiple objects
What happens to an object when it’s serialized?
But what exactly IS an object’s state? What needs to be saved?
When an object is serialized, all of the objects it refers to get serialized, too…
Use JsonSerialization to serialize your objects
JSON only includes data, not specific C# types
C# strings are encoded with Unicode
Visual Studio works really well with Unicode
.NET uses Unicode to store characters and text
C# can use byte arrays to move data around
Use a BinaryWriter to write binary data
Use BinaryReader to read the data back in
A hex dump lets you see the bytes in your files
How to make a hex dump of some plain text
Use SteamReader to build a simple hex dumper
Use Stream.Read to read bytes from a stream
Modify your hex dumper to use command-line arguments
← Prev
Back
Next →
← Prev
Back
Next →