Keith Elder
Microsoft MVP
http://keithelder.net/blog/
Assumptions
 I assume you
 Have 1 – 2 years of programming experience
 Understand the basic concepts of



Variables
Loops
Arrays
 Can type over 40 words per minute (if you are following
along)
All Lines Must End in ;
Correct
int x = 5;
Incorrect
int x = 5
Variables Must Declare Type
Correct
Incorrect
int x = 5;
x = 5;
The keyword “int” is declaring
that the value of x going to hold
an integer.
Supported C# Types
C# type keywords
.Net Framework Type
bool
System.Boolean
byte
System.Byte
sbyte
System.Sbyte
char
System.Char
decimal
System.Decimal
double
System.Double
float
System.Single
int
System.Int32
unit
System.UInt32
long
System.Int64
ulong
System.UInt64
object
System.Object
short
Sysytem.Int16
ushort
System.UInt16
string
System.String
Type Cannot Be Changed
Correct
Incorrect
int x = 5;
int x = 5;
x = “foo”;
This will result in a compile error. Once a
type has been established for a variable,
the type cannot change to another data
type.
Strings must be in quotes
Correct
Incorrect
string x = “foo bar”; string x = foo bar;
char x = ‘a’;
string x = ‘foo bar’;
char x = “a”;
Operators
 C# uses standard mathematical operators
 +, -, /, *, <, >, <=, >=,
 Expression operators
 &&
 ||
 ==
 !=
 Assignment operators
 =, +=, *=, -=, *=
http://msdn.microsoft.com/en-us/library/6a71f45d.aspx
Concatenating Strings
string x = “foo bar”;
string y = x + “ some new string”;
Case Sensitive
 Correct
int x = 5;
int Z = 5;
int y = x + Z;
 Incorrect
int x = 5;
int Z = 5;
int y = x + z;
If / Else
if (expression)
{
if (expression)
{
} else
{
} else if
(expression)
{
}
} else
{
int x = 5;
if (x > 5)
{
x = 10;
} else
{
x = 0;
}
}
TIP: If you only have one line in your if block, you can
skip the curly braces.
int x = 5;
If (x % 2 == 0)
CallSomeMethod();
Very Simple Program
class MyFirstProgram
{
static void Main()
{
int x = 5;
int y = 10;
int z = x + y;
}
}
A C# program
requires one Main
method. This is the
entry point to the
program.
All code is held within
a class.
Blocks of code are
represented with curly
braces {}.
Each line ends with a
semi-colon;
C# is a strongly typed
language.
C# is an object
oriented language
C# Quick Facts
Breaking Down C# - Namespace
Namespace
Namespace
Class
Fields and
Properties
Method1
Method2
 Abstract container providing
organization to items.
 Typically organized by:
 Company
 Product
 Team
 Sub-Team
 Etc.
 Example:

Microsoft.Learning.Csharp
Breaking Down C# - Namespace
namespace SkunkWorks
{
public class Loan
{
public decimal loanAmount;
public bool isApproved ;
}
}
namespace Vendor
{
public class Loan
{
public decimal loanAmount;
public bool isApproved ;
public int creditScore ;
}
}
Breaking Down A C# - Class
 A class is just a blue print
Namespace
Class
Fields and
Properties
Method1
Method2
for an object.
 An object is an allocated
region of storage.
 An object doesn’t exist
until memory is
allocated.
 A class holds data
(properties/fields) and is
made up of one or more
methods (functions) .
Breaking Down C# – Class
Namespace
Class
Fields and
Properties
Method1
Method2
namespace SkunkWorks
{
public class Loan
{
public decimal loanAmount;
public bool isApproved;
}
}
Class
Loan myLoan = new Loan();
When an instance of a Loan is created in
memory, this becomes an object. Thus the
variable myLoan is an object.
Fields
Breaking Down C# – Class
Class
Constructor
namespace SkunkWorks
{
public class Loan
{
public Loan()
{
}
public decimal loanAmount;
public bool isApproved;
Field and Properties
Method1
Method2
}
Class
Constructor
}
A constructor is the default “function/method”
that executes when a class is instantiated. If one
doesn’t exist, a default constructor is provided
by the compiler.
“…. Yeah but I hold the data…”
“… Oh yeah…. Well I expose the data…. So nah!”
Breaking Down C# - Fields
Fields hold data
Field Facts
 By default they are “private”




to other classes (more later)
Fields hold the data
Placed at the top of classes
outside of any methods
Private fields are usually
notated with an _
(underscore) prefix
They are named camel cased
with first letter starting with a
lowerCase
Breaking Down C# - Properties
Expose Data
Property Facts
 Used to expose field data
 Used to bind data to user




interface elements
Allows for pre and post logic
before getting or accessing data
Uses accesors to set and get field
data
Typically always marked public
(more later)
Properties always are named in
CamelCase, using no
underscores or dashes
Properties – Real World Example
Who can see what?
 Public means that anyone can access it
 Private means that only other members can access it
The field docCompleted will not be able to be viewed from classes
outside of Loan. The C# keyword private signifies it is private
within the scope of the class itself. Public means it can be seen by
other classes.
Accessing Methods and Properties
of an Instance
 Use the . (period) after the instance name of your
object to call methods in the class and access
properties.
 Intellisense will guide you in VS
•Creating a class
•Constructor
•Fields
•Properties
•Public / Private
Breaking Down C# - Methods
 Think of methods as
public class Loan
{
public decimal loanAmount;
public bool isApproved;
public void MarkApproved()
{
IsApproved = true;
OnMarkedApproved();
}
}
actions that classes can
perform.
 Take a function, put it in a
class, we call it a method.
 C# doesn’t allow functions
to live and breathe outside
of a class. Thus, all we
have is methods.
 Methods can access other
methods within the class
and properties, and call
other methods in other
classes.
Breaking Down C# - Methods
Access level
Return type
Method name
Parameters
Using Statements
using System;
using Vendor;
namespace ConsoleApplication
{
class Program
{
static void Main()
{
Loan myLoan = new Loan();
myLoan.LoanAmount = 1000000;
}
}
}
Using statements specify
which Namespaces to
use to resolve classes.
One thing we haven’t
covered
Breaking Down C# - Static
 Referenced through the type not the instance
Breaking Down C# - Static
 Can be used with
 Fields
 Methods
 Properties
 Operators
 Events
 Constructors
 Cannot be used with indexers and deconstructors
Use a Class to Define an Object
A New Object From a Class Is An
Instance
The variable lassie is the instance of the object.
Use the . (period) after the instance of your object to
call methods in the class and access properties.
Classes can be re-used
•Inheritance
•Encapsulation
•Abstraction
•Polymorphism
The Animal Object
Inheritance
Abstraction
Encapsulation
Polymorphism
Inheritance – Dogs Gone Wild
Inheritance
Constructor
Rule: Classes that are subclassed inherit all the
properties and methods of their parent class.
Although this
class doesn’t
have FurColor
in it, the value
is derived
from the base
class.
Subclasses – Different Strokes For
Different Folks
Subclasses can
implement
different
characteristics.
Subclasses can
override base
class behavior.
Adding the keyword “virtual” to a
method means it can be overridden in
a base class.
Abstraction
 Abstraction is simplifying complex reality by modeling
classes appropriate to the problem
Lassie is a
Collie
Lassie is a
dog
A dog is
an animal
Encapsulation
 Creating an object that keeps track of its state
internally using private fields and uses public
properties and methods to let other classes work with
only the part of the internal data they need to see.
Polymorphism
 This word means “Many forms”.
 It’s taking an object, and use it in a method or
statement that expects something else.
Feed takes any
Animal. We are down
casting the type to
Animal.
Interfaces – Taking Abstraction One
Step Further
 In C#, a class can only inherit from one other class
 An Interface is a way of providing abstraction
 Interfaces let you define a bunch of methods and
properties a class must have
Interfaces – Taking Abstraction One
Step Further
This class
implements
the ITremble
Interface
Interface Facts
Interfaces
Quick Facts
 Start with an uppercase I
 IDisposable, IEnumerable,
IList
 Any class that implements an
Interface has to implement
ALL methods and properties
 A class can implement one or
more Interfaces (separate the
names by comma)
 VS Shortcut Tip: Alt-ShiftF10 to implement methods
Commenting Code
 // single lines
 /// for summaries
 /* */ block
//int x = 5;
/// <summary>
/// This is what kicks the program off.
/// </summary>
/// <param name="args"></param>
static void Main(string[] args)
{
}
/* this is a comment */
Value Type vs Reference Type
foo
bar
4
int foo = 4;
string bar = “hello”;
hello
•Value Types
•int
•float
•bool
•Byte
•Reference Types
•string
•object
•list
•regex
Value Type vs Reference Type
string name = “Keith”;
string author = null;
author = name;
name
Keith
author
http://aspalliance.com/1682_What_to_Know_About_Value_Types_and_Reference_Types_in_C.all
Arrays – More than one at a time
Array Facts
 C# supports the following collections
 An array can be Single-Dimensional,





Multidimensional or Jagged.
The default value of numeric array
elements are set to zero, and reference
elements are set to null.
A jagged array is an array of arrays
Arrays are zero indexed: an array with
n elements is indexed from 0 to n-1.
Array elements can be of any type,
including an array type.
Array types are reference types derived
from the abstract base type Array.
Since this type implements
IEnumerable , you can use foreach
iteration on all arrays in C#.
Examples
Loops
 Foreach loops
 For loops
 While loops
TIP: Use code snippets to
stub these out.
foreach (var item in collection)
{
Console.WriteLine(item.Property);
}
for (int i = 0; i < length; i++)
{
Console.WriteLine(i);
}
while (expression) // x < 5
{
}
Now we are getting somewhere!
System.Collections
Collection Classes System.Collections
 Do you need a sequential list where the element is typically
discarded after its value is retrieved?
 Queue – FIFO
 Stack – LIFO
 Access by index
 ArrayList
 StringCollection
 Access by key
 Hashtable
 SortedList
 ListDictionary
 StringDictionary
 Access by key or index
 NameValueCollection
Collection Classes System.Collections
 Sort elements differently from how they were entered
 Hashtable – sorts its elements by their hash codes
 SortedList – sorts by key
 ArrayList – provides a sort method that can take an
IComparer implementation as a param
 If you need fast searches
 ListDictionary is faster than Hashtable with fewer than
10 items
 Dictionary provides faster lookup
You should thank me for showing you this.
Basics of Generics
 A generic type definition is a class, structure, or




interface declaration that functions as a template, with
placeholders for the types that it can contain or use.
System.Collections.Generics – New as of .Net 2.0
Provides a way to “generically” express re-usable code
Provides compile time type checking
Creates a shorter syntax
Basics of Generics
 List<T> is the generic
class that corresponds to
ArrayList
 The Queue<T>,
Stack<T>, and
SortedList<Tkey, Tvalue>
are generic classes
correspond to the
respective nongeneric
classes with the same
names.
Events
 Allow your objects to respond when something occurs
 An object should worry about itself, not other objects
 Baseball Simulator
 ball.OnBallInPlay(70, 82);
BallInPlay event raised
ball
pitcher object
umpire object
fan object