C#-3 Source Code Files
=== Interface1.Interface1.Program ===========================
using System;
using System.Collections;
namespace Interface1
{
///
/// Interface1 Example: Show how to implement the IComparable
/// interface to enable sorting of user defined objects.
///
public class Program
{
public static void Main()
{
// Declare and instantiate array list
ArrayList col = new ArrayList();
// Populate array list.
col.Add(new Person("Larry", 'M', 29));
col.Add(new Person("Cheryl", 'F', 32));
col.Add(new Person("Nancy", 'F', 23));
col.Add(new Person("Vince", 'M', 35));
col.Add(new Person("Charlie", 'F', 25));
// Print array list.
foreach (Object obj in col)
Console.WriteLine(obj);
// Sort array list using CompareTo method.
col.Sort();
Console.WriteLine();
// Print array list.
foreach (Object obj in col)
Console.WriteLine(obj);
Console.ReadLine();
}
}
}
--- Interface1.Interface1.Person ----------------------------
using System;
namespace Interface1
{
///
/// Interface1 Example: Show how to implement the IComparable
/// interface to enable sorting of user defined objects.
///
class Person : IComparable
{
public string Name;
public char Gender;
public int Age;
public Person(string n, char g, int a)
{
Name = n;
Gender = g;
Age = a;
}
int IComparable.CompareTo(Object other)
{
if (this.Age > ((Person)other).Age)
return 1;
else if (this.Age < ((Person)other).Age)
return -1;
else
return 0;
}
public override string ToString()
{
return Name + " " + Gender + " " + Age;
}
}
}
// Console Output:
Larry M 29
Cheryl F 32
Nancy F 23
Vince M 35
Charlie F 25
Nancy F 23
Charlie F 25
Larry M 29
Cheryl F 32
Vince M 35
=== Vector3.Vector3.Program.cs ==============================
using System;
using System.Collections;
using System.Text;
namespace Vector3
{
///
/// Vector3 Example: Show how to define overloaded operators
/// in a class.
///
public class Program
{
public static void Main()
{
ArrayList col = new ArrayList();
col.Add(new Vector(3, 4));
col.Add(new Vector(3, 2));
col.Add(new Vector(5, 1));
col.Add(new Vector(5, 5));
col.Add(new Vector(1, 9));
col.Add(new Vector(3, 2));
foreach (Vector v in col)
Console.Write(v + " ");
Console.WriteLine("\r\n");
col.Sort();
foreach (Vector v in col)
Console.Write(v + " ");
Console.ReadLine();
}
}
}
// Console Output:
(3,4) (3,2) (5,1) (5,5) (1,9) (3,2)
(1,9) (3,2) (3,2) (3,4) (5,1) (5,5)
--- Vector3.Vector3.Vector.cs -------------------------------
using System;
namespace Vector3
{
///
/// Vector3 Example: Show how to define overloaded operators
/// in a class.
///
public class Vector : IComparable
{
private int x, y;
public int CompareTo(Object other)
{
if (this.x > ((Vector)other).x)
return 1;
else if (this.x < ((Vector)other).x)
return -1;
else if (this.y > ((Vector)other).y)
return 1;
else if (this.y < ((Vector)other).y)
return -1;
else
return 0;
}
public Vector(int theX, int theY)
{
x = theX;
y = theY;
}
public override string ToString()
{
return String.Format("({0},{1})", x, y);
}
}
}
=== Delegates.Delegates.Program.cs ==========================
using System;
using System.Collections;
namespace Delegates
{
///
/// Delegates Example: This example shows a simple
/// (if somewhat hokey) use of delegates to implement a
/// version of the VB.Net CallByName function. Delegates
/// are stored in a Hashtable and accessed by key.
///
public class Program
{
public delegate double OpFunction(double x, double y);
public static Hashtable col = new Hashtable();
public static void Main()
{
// Initialize delegate collection.
col.Add("Add", new OpFunction(Add));
col.Add("Subt", new OpFunction(Subt));
col.Add("Mult", new OpFunction(Mult));
col.Add("Div", new OpFunction(Div));
Console.WriteLine(CallByName("Add", 4, 5));
Console.WriteLine(CallByName("Subt", 7, 3));
Console.WriteLine(CallByName("Mult", 2, 3));
Console.WriteLine(CallByName("Div", 9, 3));
Console.ReadLine();
}
public static double CallByName(string op, double x, double y)
{
return ((OpFunction)col[op])(x, y);
}
public static double Add(double x, double y)
{
return x + y;
}
public static double Subt(double x, double y)
{
return x - y;
}
public static double Mult(double x, double y)
{
return x * y;
}
public static double Div(double x, double y)
{
return x / y;
}
}
}
// Console Output:
9
4
6
3
=== RaiseEvent.RaiseEvent.Form1.cs ==========================
using System;
using System.Collections;
using System.ComponentModel;
using System.Drawing;
using System.Windows.Forms;
namespace RaiseEvent
{
///
/// RaiseEvent Example: Show how to declare and use an event
/// in a class.
///
public partial class Form1 : Form
{
// Use ArrayList collection to hold Person objects.
public ArrayList col = new ArrayList();
public Form1()
{
InitializeComponent();
}
// Create Person object and corresponding event.
private void btnCreate_Click(object sender, EventArgs e)
{
string n = txtName.Text;
string g = label2.Text;
int a = int.Parse(txtAge.Text);
Person p = new Person(n, g, a);
cboPersons.Items.Add(p);
p.AgeReached += new Person.AgeReachedEventHandler(p_AgeReached);
}
// Cause selected Person object to have a birthday.
private void btnBirthday_Click(object sender, EventArgs e)
{
if (cboPersons.SelectedIndex > -1)
{
Person p = (Person) (cboPersons.SelectedItem);
p.HaveBirthday();
}
}
// Event handler for Person.AgeReached event.
private void p_AgeReached(Person p)
{
MessageBox.Show("Age 65 Reached for Person:\r\n" +
p.Name + " " + p.Gender + " " + p.Age);
}
}
}
--- RaiseEvent.RaiseEvent.Person.cs -------------------------
using System;
namespace RaiseEvent
{
///
/// RaiseEvent Example: Show how to declare and use an event
/// in a class.
///
public class Person
{
private string name;
private string gender;
private int age;
// Delegate to be used for event handler.
public delegate void AgeReachedEventHandler(Person p);
// Event must be declared with a delegate for event handler.
public event AgeReachedEventHandler AgeReached;
// Person constructor.
public Person(string n, string g, int a)
{
name = n;
gender = g;
age = a;
}
// Properties for Person object.
public string Name
{
get { return name; }
}
public string Gender
{
get { return gender; }
}
public int Age
{
get { return age; }
}
// Add one to age when object has a birthday.
public void HaveBirthday()
{
age++;
if (age == 65)
AgeReached(this);
}
// ToString method determines what is shown in the
// combo box.
public override string ToString()
{
return name;
}
}
}
// Console Output:
=== BoxUnbox.BoxUnbox.Program.cs ============================
using System;
using System.Drawing;
using System.Collections;
namespace BoxUnbox
{
///
/// BoxUnbox Example
/// Show how adding value type objects to an ArrayList can
/// lead to unexpected results when trying to change the
/// values in the objects.
///
public class Program
{
public static void Main()
{
// Create new ArrayList collection.
ArrayList rects = new ArrayList(5);
// Add 5 value type Rectangle objects to an ArrayList.
// The rectangle objects are boxed when they are added
// to the collection
for(int i = 0; i < 5; i++)
rects.Add(new Rectangle(0, 0, 100, 100));
// Increase the size of each rectangle.
for (int i = 0; i < 5; i++)
((Rectangle)rects[i]).Inflate(200, 200);
// Print the rectangles that are still in the collection.
for (int i = 0; i < 5; i++)
Console.WriteLine(rects[i]);
Console.ReadLine();
}
}
}
// Console Output:
{X=0,Y=0,Width=100,Height=100}
{X=0,Y=0,Width=100,Height=100}
{X=0,Y=0,Width=100,Height=100}
{X=0,Y=0,Width=100,Height=100}
{X=0,Y=0,Width=100,Height=100}
=== Generic1.Generic1.Program.cs ============================
using System;
using System.Collections.Generic;
namespace Generic1
{
///
/// Generic1 Example: Compare a user defined collection class
/// with a generic List class.
///
public class Program
{
public static void Main()
{
// Declare, instantiate and populate nongeneric collection.
Vehicle x = new Vehicle("Ford Taurus", 1999, 90000);
VehicleCollection vc = new VehicleCollection();
vc.Add(x);
vc.Add("Volkswagon Jetta", 2005, 20000);
// Print objects in generic collection.
Console.WriteLine("Count of vc is " + vc.Count);
Console.WriteLine(vc);
foreach (Vehicle v in vc)
Console.WriteLine(v);
Console.WriteLine("\r\n************\r\n");
// Declare, instantiate and populate nongeneric collection.
List gc = new List();
gc.Add(x);
gc.Add(new Vehicle("Volkswagon Jetta", 2005, 20000));
// Print objects in generic collection.
Console.WriteLine("Count of gc is " + gc.Count);
Console.WriteLine(gc);
foreach(Vehicle v in gc)
Console.WriteLine(v);
Console.ReadLine();
}
}
}
// Console Output:
Count of vc is 2
[Ford Taurus 1999 90000,
Volkswagon Jetta 2005 2000]
Ford Taurus 1999 90000
Volkswagon Jetta 2005 20000
************
Count of gc is 2
System.Collections.Generic.List`1[Generic1.Vehicle]
Ford Taurus 1999 90000
Volkswagon Jetta 2005 20000
--- Generic1.Generic1.Vehicle.cs ----------------------------
using System;
namespace Generic1
{
///
/// Generic1 Example: Compare a user defined collection class
/// with a generic List class.
///
public class Vehicle
{
private string mvarModel;
private int mvarYear;
private int mvarMiles;
public Vehicle(string theModel)
{
if (theModel != "")
mvarModel = theModel;
else
mvarModel = "Unknown";
mvarYear = DateTime.Now.Year;
mvarMiles = 0;
}
public Vehicle(string theModel, int theYear, int theMiles)
{
if (theModel != "")
mvarModel = theModel;
else
mvarModel = "Unknown";
mvarYear = theYear;
if (theMiles >= 0)
mvarMiles = theMiles;
else
mvarMiles = 0;
}
public string Model
{
get { return mvarModel; }
}
public int Year
{
get { return mvarYear; }
}
public int Miles
{
get { return mvarMiles; }
set
{
if (value > mvarMiles)
mvarMiles = value;
}
}
public override string ToString()
{
return mvarModel + " " + mvarYear + " " + mvarMiles;
}
}
}
--- Generic1.Generic1.VehicleCollection.cs ------------------
using System;
using System.Collections;
namespace Generic1
{
///
/// Generic1 Example: Compare a user defined collection class
/// with a generic List class.
///
class VehicleCollection : IEnumerable
{
private ArrayList col;
public VehicleCollection()
{
col = new ArrayList();
}
public IEnumerator GetEnumerator()
{
return col.GetEnumerator();
}
public int Count
{
get { return col.Count; }
}
public int Add(Vehicle v)
{
col.Add(v);
return col.Count;
}
public int Add(string theMake, int theYear, int theMiles)
{
col.Add(new Vehicle(theMake, theYear, theMiles));
return col.Count;
}
public void RemoveAt(int i)
{
col.RemoveAt(i);
}
public override string ToString()
{
string s = "[";
foreach (Object obj in col)
s += obj.ToString() + ",\r\n";
s = s.Substring(0, s.Length - 4) + "]";
return s;
}
}
}
=== Generic2.Generic2.Program.cs ============================
using System;
using System.Collections.Generic;
namespace Generic2
{
///
/// Generic2 Example: Show how to define a user defined generic
/// collection. The FindMax method returns the "largest" object
/// as defined by the objects CompareTo method. The collection
/// also has a ToString method for printing the entire collection.
///
public class Program
{
public static void Main()
{
MyCollection sc = new MyCollection();
sc.Add(new Vehicle("Ford Taurus", 1997, 90000, 25.8));
sc.Add(new Vehicle("Volkswagon Jetta", 2005, 20000, 23.5));
sc.Add(new Vehicle("Toyota Prius", 2006, 70000, 26.0));
sc.Add(new Vehicle("BW Abc", 1997, 50000, 20.3));
sc.Add(new Vehicle("Toyota Corolla", 1997, 30000, 21.5));
Console.WriteLine(sc + "\r\n");
Console.WriteLine(sc.FindMaxObject());
Console.ReadLine();
}
}
}
// Console Output:
[Ford Taurus 1997 90000 25.8,
Volkswagon Jetta 2005 20000 23.5,
Toyota Prius 2006 70000 26,
BW Abc 1997 50000 20.3,
Toyota Corolla 1997 30000 21.5]
Toyota Prius 2006 70000 26
--- Generic2.Generic2.Vehicle.cs ----------------------------
using System;
namespace Generic2
{
///
/// Generic2 Example: Compares a user defined collection class
/// with a generic List class.
///
public class Vehicle : IComparable
{
public string Model;
public int Year;
public int Miles;
public double Mpg;
public Vehicle(string model, int year, int miles, double mpg)
{
Model = model;
Year = year;
Miles = miles;
Mpg = mpg;
}
public override string ToString()
{
return Model + " " + Year + " " + Miles + " " + Mpg;
}
public int CompareTo(Object other)
{
double epsilon = 0.000001;
if (Mpg - ((Vehicle)other).Mpg > epsilon)
return 1;
else if (Mpg - ((Vehicle)other).Mpg < epsilon)
return -1;
else
return 0;
}
}
}
--- Generic2.Generic2.MyCollection.cs -----------------------
using System;
using System.Collections;
using System.Collections.Generic;
namespace Generic2
///
/// Generic2 Example: Show how to define a user defined generic
/// collection. The FindMax method returns the "largest" object
/// as defined by the objects CompareTo method. The collection
/// also has a ToString method for printing the entire collection.
///
///
/// Parameter defines the type of objects
/// allowed in the collection
///
{
public class MyCollection : IEnumerable
{
private List col;
public MyCollection()
{
col = new List();
}
IEnumerator IEnumerable.GetEnumerator()
{
return col.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return col.GetEnumerator();
}
public int Count
{
get { return col.Count; }
}
public void Add(T item)
{
col.Add(item);
}
public void RemoveAt(int i)
{
col.RemoveAt(i);
}
public T FindMaxObject()
{
IComparable max = (IComparable)col[0];
foreach (T obj in col)
{
IComparable x = (IComparable)obj;
if (max.CompareTo(x) < 0)
max = x;
}
return (T)max;
}
public override string ToString()
{
string s = "[";
foreach (Object obj in col)
s += obj.ToString() + ",\r\n";
s = s.Substring(0, s.Length - 3) + "]";
return s;
}
}
}
=== Generic3.Generic3.Program.cs ============================
using System;
using System.Collections.Generic;
using System.Text;
namespace Generic3
{
///
/// Generic3 Example: Show how to define a user defined generic
/// collection that can access objects either by index or by key.
///
public class Program
{
public static void Main()
{
// Declare, instantiate and populate collection of vehicles.
MyCollection a = new MyCollection();
a.Add("car3", new Vehicle("Ford Taurus", 2000, 75000));
a.Add("car2", new Vehicle("VW Passat", 2000, 75000));
a.Add("car1", new Vehicle("Mitubishi Eclipse", 2000, 75000));
a.Add(new Vehicle("Toyota Corolla", 2000, 75000));
a.Add("car2", new Vehicle("Toyota Prius", 2006, 100));
// Access items in collection by index.
for (int i = 0; i < a.Count; i++)
Console.WriteLine(a[i]);
Console.WriteLine();
foreach(Vehicle v in a)
Console.WriteLine(v);
Console.WriteLine();
// Access items in collection by key.
Console.WriteLine(a["car1"]);
Console.WriteLine(a["car2"]);
Console.WriteLine(a["car3"]);
Console.WriteLine(a["car4"]);
Console.WriteLine(a[""]);
Console.ReadLine();
}
}
}
// Console Output:
Ford Taurus 2000 75000
VW Passat 2000 75000
Mitubishi Eclipse 2000 75000
Toyota Corolla 2000 75000
Toyota Prius 2006 100
Ford Taurus 2000 75000
VW Passat 2000 75000
Mitubishi Eclipse 2000 75000
Toyota Corolla 2000 75000
Toyota Prius 2006 100
Mitubishi Eclipse 2000 75000
VW Passat 2000 75000
Ford Taurus 2000 75000
Toyota Corolla 2000 75000
--- Generic3.Generic3.Vehicle.cs ----------------------------
using System;
namespace Generic3
{
///
/// Generic3 Example: Show how to define a user defined
/// generic collection that can access objects either by
/// index or by key.
///
public class Vehicle
{
private string mvarModel;
private int mvarPurchaseDate;
private int mvarMiles;
public Vehicle(string theModel,
int thePurchaseDate, int theMiles)
{
mvarModel = theModel;
mvarPurchaseDate = thePurchaseDate;
if (theMiles >= 0)
mvarMiles = theMiles;
else
mvarMiles = 0;
}
public string Model
{
get { return mvarModel; }
}
public int Year
{
get { return mvarPurchaseDate; }
}
public int Miles
{
get { return mvarMiles; }
set
{
if (value > mvarMiles)
mvarMiles = value;
}
}
public override string ToString()
{
return mvarModel + " " + mvarPurchaseDate + " " + mvarMiles;
}
}
}
--- Generic3.Generic3.MyCollection.cs -----------------------
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
namespace Generic3
{
///
/// Generic3 Example: Show how to define a user defined
/// generic collection that can access objects either by
/// index or by key.
///
///
/// Parameter defines the type of objects
/// allowed in the collection
///
public class MyCollection : IEnumerable
{
// Declare instance variables.
private List col = new List();
private List keys = new List();
// Define method required by IEnumerable.
public IEnumerator GetEnumerator()
{
return col.GetEnumerator();
}
// Define method required by IEnumerable.
IEnumerator IEnumerable.GetEnumerator()
{
return col.GetEnumerator();
}
// Define collection Add methods.
public void Add(T item)
{
col.Add(item);
keys.Add("");
}
public void Add(string key, T item)
{
col.Add(item);
keys.Add(key);
}
// Define collection Count property.
public int Count
{
get { return col.Count; }
}
// Define indexers
public T this[int index]
{
get { return col[index]; }
set { col[index] = value; }
}
public T this[string key]
{
get
{
for(int i = 0; i < col.Count; i++)
if (key == keys[i])
return col[i];
return default(T);
}
set
{
for(int i = 0; i < col.Count; i++)
if (key == keys[i])
{
col[i] = value;
break;
}
}
}
}
}
=== Vector2.Vector2.Program.cs ==============================
using System;
namespace Vector2
{
///
/// Vector2 Example: Show how to overload the +, -, *, ==,
/// and != operators.
///
///
/// When overloading ==, != and GetHashCode must also be
/// overloaded. When + and - are overloaded, += and -= are
/// overloaded automatically. *= cannot be used because it does
/// not have the signature (Vector, Vector).
///
public class Program
{
public static void Main()
{
Vector p = new Vector(2, 3);
Vector q = new Vector(4, 5);
Vector r = new Vector(2, 3);
Console.WriteLine("{0} {1} {2}",
p + q, p - q, 2 * p);
Console.WriteLine("{0} {1} {2} {3} {4}\r\n",
p == q, p != q, p == r, p != r,
Vector.ReferenceEquals(p, r));
Console.WriteLine(Convert.ToString(p.GetHashCode(), 16));
Console.ReadLine();
}
}
}
// Console Output:
(6,8) (-2,-2) (4,6)
False True True False False
b1528023
--- Vector2.Vector2.Vector.cs -------------------------------
using System;
namespace Vector2
{
///
/// Vector2 Example: Illustrates how to overload operators.
///
public class Vector
{
public int x, y;
public Vector(int xVal, int yVal)
{
x = xVal;
y = yVal;
}
public override string ToString()
{
return "(" + x + "," + y + ")";
}
public static Vector operator +(Vector v, Vector w)
{
return new Vector(v.x + w.x, v.y + w.y);
}
public static Vector operator -(Vector v, Vector w)
{
return new Vector(v.x - w.x, v.y - w.y);
}
public static Vector operator *(int a, Vector v)
{
return new Vector(a * v.x, a * v.y);
}
public override bool Equals(object other)
{
return this.x == ((Vector)other).x &&
this.y == ((Vector)other).y;
}
public override int GetHashCode()
{
return this.ToString().GetHashCode();
}
public static bool operator ==(Vector v, Vector w)
{
return v.Equals(w);
}
public static bool operator !=(Vector v, Vector w)
{
return !(v == w);
}
}
}
=== Explicit.Explicit.Program.cs ============================
using System;
using System.ComponentModel;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Windows.Forms;
namespace Explicit
{
///
/// Explicit Example: Show how to use the explicit and implicit
/// keywords to create custom cast operators for converting a
/// Square object to a Rect object and vice versa.
///
///
/// A square is implicitly converted to a rectangle but the keyword
/// explicit is used to convert to a square to a rectangle because
/// it is not obvious how the conversion should be accomplished.
///
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
MessageBox.Show("Click on form to display objects.");
}
private void Form1_Click(object sender, EventArgs e)
{
Rect r = new Rect(160, 125);
Square s = (Square)r;
Rect t = s;
r.Display(10, 10, this);
s.Display(200, 10, this);
t.Display(400, 10, this);
}
}
}
--- Explicit.Explicit.Rect.cs -------------------------------
using System;
using System.Drawing;
namespace Explicit
{
///
/// Explicit Example: Show how to use the explicit and implicit
/// keywords to create custom cast operators for converting a
/// Square object to a Rect object and vice versa.
///
///
/// When a Rect object is converted to a Square object, assign the
/// square that has the same area as the rectangle.
///
public class Rect
{
private float width, height;
public float Height
{
get { return height; }
}
public float Width
{
get { return width; }
}
public Rect(float w, float h)
{
width = w;
height = h;
}
public virtual void Display(float left, float top, Form1 f)
{
Graphics g = f.CreateGraphics();
Brush b = new SolidBrush(Color.Black);
g.FillRectangle(b, left, top, this.Width, this.Height);
g.Dispose();
}
public static implicit operator Rect(Square sqr)
{
return new Rect(sqr.Side, sqr.Side);
}
}
}
--- Explicit.Explicit.Square.cs -----------------------------
using System;
using System.Drawing;
namespace Explicit
{
///
/// Explicit Example: Show how to use the explicit and implicit
/// keywords to create custom cast operators for converting a
/// Square object to a Rect object and vice versa.
///
public class Square
{
private float side;
public Square(float s)
{
side = s;
}
public float Side
{
get { return side; }
}
public void Display(float left, float top, Form1 f)
{
Graphics g = f.CreateGraphics();
Brush b = new SolidBrush(Color.Black);
g.FillRectangle(b, left, top, this.Side, this.Side);
}
public static explicit operator Square(Rect r)
{
float s = (float)Math.Sqrt(r.Width * r.Height);
return new Square(s);
}
}
}
======= NewStuff.NewStuff.Program.cs =================================
using System;
using System.Collections.Generic;
///
/// Illustrate some 2008 features of C#.
///
namespace NewStuff
{
public static class Program
{
public static void Main()
{
// 1. Implicit data typing.
var m = 3;
var x = 3.14;
var flag = true;
var s = "abc";
Console.WriteLine("{0} {1} {2} {3}", m, x, flag, s);
Console.WriteLine("{0} {1} {2} {3}",
m.GetType().Name, x.GetType().Name,
flag.GetType().Name, s.GetType().Name);
Console.WriteLine();
// 2. An extension method.
// Extension methods must be defined in a static class.
Person p = new Person("Alice", 'F', 23);
p.HasBirthday();
Console.WriteLine(p);
Console.WriteLine();
// 3. An object initializer.
var q = new Point { X = 30, Y = 40 };
Console.WriteLine(q);
Console.WriteLine();
// 4. An anonymous type.
var myCar = new {Color = "Red", Make = "Buick", Year = 1975};
Console.WriteLine(myCar);
Console.WriteLine(myCar.Color);
Console.WriteLine();
// 5. Using a selector predicate using a traditional method.
// A delegate can also be passed instead of FindAll.
List numbers = new List() { 22, 51, 48, 39 };
List evenOnly1 = numbers.FindAll(IsEven);
foreach (int n in evenOnly1)
Console.WriteLine(n);
Console.WriteLine();
// 6. Using a selector method with anonymous delegate syntax.
List evenOnly2 =
numbers.FindAll(delegate(int i)
{ return i % 2 == 0; });
foreach (int n in evenOnly2)
Console.WriteLine(n);
Console.WriteLine();
// 7. Using a selector method with lambda syntax.
List evenOnly3 = numbers.FindAll(i => (i % 2) == 0);
foreach (int n in evenOnly3)
Console.WriteLine(n);
Console.ReadLine();
}
// New extension method for Person object.
public static void HasBirthday(this Person thePerson)
{
thePerson.Age++;
}
// Selector method for items 5, 6 and 7.
public static bool IsEven(int i)
{
return i % 2 == 0;
}
}
}
// Console Output:
3 3.14 True abc
Int32 Double Boolean String
Alice F 24
(30, 40)
{ Color = Red, Make = Buick, Year = 1975 }
Red
22
48
22
48
22
48
======= GarbageCollector.GarbageCollector.Program.cs =================
using System;
namespace GarbageCollector
{
///
/// GarbageCollector Example: Create three objects with a
/// circular reference to see if the garbage collector is fooled.
///
public class Program
{
public static void Main()
{
Vector v;
// Create three Vector objects.
v = new Vector(1, 1);
v.link = new Vector(2, 2);
v.link.link = new Vector(3, 3);
// The next link creates the circular link.
v.link.link.link = v;
// Print Vector objects.
Console.WriteLine(v);
Console.WriteLine(v.link);
Console.WriteLine(v.link.link);
Console.WriteLine(v.link.link.link);
Console.WriteLine("The four Vector objects are now in memory.");
Console.WriteLine("Press Enter key to turn objects into garbage.");
Console.ReadLine();
// Make some garbage:
v = null;
Console.WriteLine("Maximum generations supported by GC: " +
GC.MaxGeneration);
Console.WriteLine("Press Enter key to invoke garbage collector");
Console.WriteLine("and see output from destructor method calls.");
Console.ReadLine();
// Invoke garbage collector, which invokes the Finalize methods.
GC.Collect();
Console.ReadLine();
}
}
}
// Console Output:
(1,1)
(2,2)
(3,3)
(1,1)
The four Vector objects are now in memory.
Press Enter key to turn objects into garbage.
Maximum generations supported by GC: 2
Press Enter key to invoke garbage collector
and see output from destructor method calls.
(1,1)
(2,2)
(3,3)
------- GarbageCollector.GarbageCollector.Point.cs -------------------
using System;
namespace GarbageCollector
{
///
/// GarbageCollector Example: Create three objects with a
/// circular reference to see if the garbage collector is fooled.
///
public class Vector
{
// Public instance variables
public int x, y;
public Vector link;
public Vector(int x, int y)
{
this.x = x;
this.y = y;
this.link = null;
}
public override string ToString()
{
return "(" + x + "," + y + ")";
}
// Instead of overriding Finalize like this,
// provide a destructor
// protected override void Finalize()
// {
// Console.WriteLine(this);
// }
~Vector()
{
Console.WriteLine(this);
}
}
}
======= IDisposable.IDisposable.Program.cs ===========================
using System;
namespace Disposable
{
///
/// IDisposable Example: Illustrates how to implement the
/// IDisposable interface by supplying a Dispose method.
///
public class Program
{
public static void Main(string[] args)
{
string line;
WebPageDownloader d = new WebPageDownloader(
"http://condor.depaul.edu/~sjost/test-download.htm");
line = d.GetLine();
while (line != null)
{
Console.WriteLine(line);
line = d.GetLine();
}
d.Dispose();
Console.ReadLine();
}
}
}
// Console Output:
fox
beaver
deer
mouse
raccoon
oppossum
squirrel
------- IDisposable.IDisposable.WebPageDownloader.cs -----------------
using System;
using System.IO;
using System.Net;
namespace Disposable
{
///
/// IDisposable Example: Illustrate how to implement the
/// IDisposable interface by supplying a Dispose method.
///
public class WebPageDownloader : IDisposable
{
private string uri;
private WebResponse response;
private Stream stream;
private StreamReader reader;
private HttpWebRequest request;
private bool responseObtained;
private bool disposed;
public WebPageDownloader(string theUri)
{
uri = theUri;
// Create HttpWebRequest object but wait
// to get response until needed.
request = (HttpWebRequest) WebRequest.Create(uri);
responseObtained = false;
disposed = false;
}
public string GetLine()
{
// If response has not yet been
// obtained, obtain response.
if (!responseObtained)
{
try
{
response = request.GetResponse();
stream = response.GetResponseStream();
reader = new StreamReader(stream);
responseObtained = true;
}
catch (UriFormatException e)
{
Console.WriteLine(e);
}
}
return reader.ReadLine();
}
public void Dispose()
{
this.Dispose(true);
// After calling Dispose explicitly, take object
// off of the finalization queue to prevent Dispose
// from being called again.
GC.SuppressFinalize(this);
}
// The parameterized version of Dispose operates
// in two modes:
// (1) If its parameter is True, Dispose has been called
// directly or indirectly by the user's code.
// (2) If its parameter is False, Dispose has been called
// by the runtime from within the Finalize method.
// Other objects should not be referenced because the
// garbage collector may have already reclaimed them.
protected virtual void Dispose(bool disposing)
{
// If Dispose has already been called, do not
// try to dispose resources again.
if (!disposed)
{
// Dispose unmanaged resources
response.Close();
stream.Close();
reader.Close();
if (disposing)
{
// Dispose managed resources.
request = null;
response = null;
stream = null;
reader = null;
}
disposed = true;
}
}
// Finalize is called automatically by the
// garbage collector. Finalize should not be
// called explicitly except by the base class.
~WebPageDownloader()
{
// Garbage collector will automatically
// reclaim managed resources, so destructor
// should only worry about unmanaged resources.
Dispose(false);
}
}
}
======= ICloneable.ICloneable.Program.cs =============================
using System;
namespace Cloneable
{
///
/// IClonable Example: Show how to clone a deep copy
/// using recursion.
///
public class Program
{
public static void Main()
{
Person p = new Person("Susan", 'F', 59);
Person q;
Console.WriteLine("Person object p");
p.Add("Tom", 'M', 25);
p.Add("Jason", 'M', 23);
p.Add("Ashley", 'M', 19);
p[1].Add("Scott", 'M', 2);
Console.WriteLine(p);
Console.WriteLine("Cloned Person object q");
q = (Person)p.Clone();
Console.WriteLine(q);
Console.WriteLine();
Console.WriteLine("p after adding another grandchild");
p[0].Add("Lucy", 'F', 0);
Console.WriteLine(p);
Console.WriteLine();
Console.WriteLine("q is unchanged.");
Console.WriteLine(q);
Console.ReadLine();
}
}
}
// Console Output:
Person object p
Susan F 59
Tom M 25
Jason M 23
Scott M 2
Ashley M 19
Cloned Person object q
Susan F 59
Tom M 25
Jason M 23
Scott M 2
Ashley M 19
p after adding another grandchild
Susan F 59
Tom M 25
Lucy F 0
Jason M 23
Scott M 2
Ashley M 19
q is unchanged.
Susan F 59
Tom M 25
Jason M 23
Scott M 2
Ashley M 19
------- ICloneable.ICloneable.Person.cs ------------------------------
using System;
using System.Collections;
namespace Cloneable
{
///
/// IClonable Example: Show how to clone a deep copy
/// using recursion.
///
public class Person : ICloneable
{
private string mvarName;
private char mvarGender;
private int mvarAge;
private ArrayList mvarChildren;
public Person(string theName, char theGender, int theAge)
{
mvarName = theName;
mvarGender = theGender;
mvarAge = theAge;
mvarChildren = new ArrayList();
}
public string Name
{
get { return mvarName; }
}
public char Gender
{
get { return mvarGender; }
}
public int Age
{
get { return mvarAge; }
}
public Person this[int index]
{
get { return (Person) mvarChildren[index]; }
}
public void Add(string theName, char theGender, int theAge)
{
mvarChildren.Add(new Person(theName, theGender, theAge));
}
public override string ToString()
{
string r;
r = mvarName + " " + mvarGender + " " + mvarAge + "\r\n";
foreach(Person k in mvarChildren)
r += k.ToString();
return r;
}
public object Clone()
{
Person p = new Person(mvarName, mvarGender, mvarAge);
foreach (Person k in mvarChildren)
{
p.mvarChildren.Add(k.Clone());
}
return p;
}
}
}
======= FileIO2.FileIO2.Program.cs ===================================
using System;
using System.IO;
using System.Windows.Forms;
namespace FileIO2
{
///
/// FileIO2 Example: Create a StreamReader from
/// a FileStream object and setting the current
/// directory.
///
public class Program
{
public static void Main()
{
// Declare variables
int count = 0, sum = 0;
double ave = 0;
string line;
// See what happens when the following two lines are
// uncommented:
// Directory.SetCurrentDirectory(
// Directory.GetCurrentDirectory() + "/..");
// Set input file name.
string infileName = "../../numbers.txt";
// It is safer to replace the previous line by the
// following ones. A reference to System.Windows.Forms is needed.
// string infileName = Application.StartupPath + "/../../numbers.txt";
// Create FileStream object
FileStream inStream = new FileStream(infileName, FileMode.Open,
FileAccess.Read, FileShare.Read);
// Create StreamReader Object
StreamReader infile = new StreamReader(inStream);
// Compute average of integers in file.
while (infile.Peek() > -1)
{
line = infile.ReadLine();
sum += int.Parse(line);
count += 1;
}
// Close input file.
infile.Close();
// Create output FileStream Object
string outfileName = "average.txt";
FileStream outStream = new FileStream(outfileName,
FileMode.Create, FileAccess.Write, FileShare.None);
// Create StreamWriter Object
StreamWriter outfile = new StreamWriter(outStream);
// Compute average and write is to output file.
ave = sum / count;
outfile.WriteLine("The average is " + ave + ".");
outfile.Close();
// Announce that program has finished.
Console.WriteLine("Average computed.");
Console.ReadLine();
}
}
}
// Console Output:
Average computed
// Input File numbers.txt:
54
34
67
65
53
// Output File:
The average is 54.
------- Collections.Collections.Person.cs ----------------------------
using System;
///
/// Illustrate some 2008 features of C#.
///
namespace Col
{
public class Person
{
private string name;
private char gender;
private int age;
public Person(string theName, char theGender, int theAge)
{
name = theName;
gender = theGender;
age = theAge;
}
public string Name
{
get { return name; }
}
public char Gender
{
get { return gender; }
}
public int Age
{
get { return age; }
set { age = value; }
}
public override string ToString()
{
return string.Format("{0} {1} {2}", name, gender, age);
}
}
}
======= Generics.Generics.Program.cs =================================
using System;
using System.Collections.Generic;
///
/// Show these collections.
/// 1. Stack, 2. Queue, 3. SortedDictionary
/// Compare with the Collections Example.
///
namespace Col
{
public class Program
{
public static void Main(string[] args)
{
Console.WriteLine("1. Stack.");
Stack s = new Stack();
s.Push("fox");
s.Push("deer");
s.Push("raccoon");
Console.WriteLine(s.Peek());
s.Pop();
s.Pop();
Console.WriteLine(s.Peek());
s.Push("rabbit");
// Print resulting stack with foreach statement.
foreach (object x in s)
Console.Write(x + " ");
Console.WriteLine();
// Print resulting stack with explicit enumerator.
IEnumerator e = s.GetEnumerator();
while (e.MoveNext())
Console.Write(e.Current + " ");
Console.WriteLine("\n");
Console.WriteLine("2. Queue.");
Queue q = new Queue();
q.Enqueue("deer");
q.Enqueue("raccoon");
q.Enqueue("skunk");
Console.WriteLine(q.Peek());
q.Dequeue();
q.Dequeue();
Console.WriteLine(q.Peek());
q.Enqueue("rabbit");
// Print resulting stack with foreach statement.
foreach (object x in q)
Console.Write(x + " ");
Console.WriteLine();
// Print resulting stack with explicit enumerator.
e = s.GetEnumerator();
while (e.MoveNext())
Console.Write(e.Current + " ");
Console.WriteLine("\n");
Console.WriteLine("3. SortedDictionary.");
SortedDictionary col =
new SortedDictionary();
col.Add("Jane", new Person("Jane", 'F', 29));
col.Add("Tom", new Person("Tom", 'M', 33));
col.Add("Alice", new Person("Alice", 'F', 35));
col.Add("Scott", new Person("Scott", 'M', 39));
col.Add("Chloe", new Person("Chloe", 'F', 32));
Console.WriteLine(col["Alice"]);
col.Remove("Tom");
Console.WriteLine();
// Print resulting stack with foreach statement.
foreach (object p in col.Values)
Console.WriteLine(p);
Console.WriteLine();
// Print resulting stack with explicit enumerator.
IEnumerator d = col.Values.GetEnumerator();
while (d.MoveNext())
Console.WriteLine(d.Current);
Console.WriteLine("\n");
Console.ReadLine();
}
}
}
// Console Output:
1. Stack.
raccoon
fox
rabbit fox
rabbit fox
2. Queue.
deer
skunk
skunk rabbit
rabbit fox
3. SortedDictionary.
Alice F 35
Alice F 35
Chloe F 32
Jane F 29
Scott M 39
Alice F 35
Chloe F 32
Jane F 29
Scott M 39
=== BitArray.BitArray.Program.cs ============================
using System;
using System.Collections;
namespace BA
{
///
/// BitArray Example: A BitArray collection stores bits
/// in an efficient data structure. The bitwise operations
/// And, Or, XOr, and Not can be used. For example, the
/// statement x.Or(y) computes the bitwise or of x and y,
/// then puts the result in x.
///
public class Program
{
public static void Main()
{
BitArray x, y;
// Compute Bitwise And of x and y.
x = FromBitString("0101");
y = FromBitString("1100");
x.And(y);
Console.WriteLine("Bitwise And:" + " " + ToBitString(x));
// Compute Bitwise Or of x and y.
x = FromBitString("0101");
y = FromBitString("1100");
x.Or(y);
Console.WriteLine("Bitwise Or:" + " " + ToBitString(x));
// Compute Bitwise Xor of x and y.
x = FromBitString("0101");
y = FromBitString("1100");
x.Xor(y);
Console.WriteLine("Bitwise XOr:" + " " + ToBitString(x));
// Compute Bitwise Not of x and y.
x = FromBitString("0101");
x.Not();
Console.WriteLine("Bitwise Not:" + " " + ToBitString(x));
Console.WriteLine();
Console.WriteLine("Length of BitArray: " + x.Length);
Console.WriteLine();
Console.WriteLine("Contents of BitArray:");
foreach (object t in y)
Console.WriteLine(t);
Console.ReadLine();
}
private static BitArray FromBitString(string bitString)
{
int len = bitString.Length;
BitArray ba = new BitArray(bitString.Length);
for (int i = 0; i < len; i++)
switch (bitString.Substring(i, 1))
{
case "0": ba[i] = false;
break;
case "1": ba[i] = true;
break;
}
return ba;
}
private static string ToBitString(BitArray ba)
{
string bs = "";
foreach (bool bit in ba)
switch (bit)
{
case false: bs += "0";
break;
case true: bs += "1";
break;
}
return bs;
}
}
}
// Console Output:
Bitwise And: 0100
Bitwise Or: 1101
Bitwise XOr: 1001
Bitwise Not: 1010
Length of BitArray: 4
Contents of BitArray:
True
True
False
False
======= Indexer.Indexer.Program.cs ===================================
using System;
using System.Collections;
namespace Indexer
{
///
/// Indexer Example: Show how to implement a custom indexer.
/// This example uses two overloaded indexers.
///
public class Program
{
public static void Main()
{
StateInfo x = new StateInfo("Illinois", "Springfield",
"Chicago", "Cardinal", "Purple Violet");
// Retrieve items by index.
for(int i = 0; i <= 4; i++)
Console.WriteLine(x[i]);
Console.WriteLine();
// Retrieve items by key.
Console.WriteLine(x["name"]);
Console.WriteLine(x["capitol"]);
Console.WriteLine(x["largestcity"]);
Console.WriteLine(x["bird"]);
Console.WriteLine(x["flower"]);
Console.WriteLine();
// Print items using ToString method.
Console.WriteLine(x);
Console.ReadLine();
}
}
}
// Console Output:
Illinois
Springfield
Chicago
Cardinal
Purple Violet
Illinois
Springfield
Chicago
Cardinal
Purple Violet
Name: Illinois
Capitol: Springfield
Largest City: Chicago
State Bird: Cardinal
State Flower: Purple Violet
------- Indexer.Indexer.StateInfo.cs ---------------------------------
using System;
using System.Collections;
namespace Indexer
{
///
/// Indexer Example: Show how to implement a custom indexer.
/// This example uses two overloaded indexers.
///
public class StateInfo
{
private string name, capitol, largestCity, bird, flower;
// Parameterized constructor.
public StateInfo(string theName, string theCapitol,
string theLargestCity, string theBird, string theFlower)
{
name = theName;
capitol = theCapitol;
largestCity = theLargestCity;
bird = theBird;
flower = theFlower;
}
// Indexer that works for numeric indices.
public string this[int index]
{
get
{
string returnValue;
switch (index)
{
case 0: returnValue = name; break;
case 1: returnValue = capitol; break;
case 2: returnValue = largestCity; break;
case 3: returnValue = bird; break;
case 4: returnValue = flower; break;
default: return "Illegal index.";
}
return returnValue;
}
}
// Indexer that works for numeric indices.
public string this[string key]
{
get
{
string returnValue;
switch (key)
{
case "name": returnValue = name; break;
case "capitol": returnValue = capitol; break;
case "largestcity":returnValue = largestCity; break;
case "bird": returnValue = bird; break;
case "flower": returnValue = flower; break;
default: return "Illegal index.";
}
return returnValue;
}
}
public override string ToString()
{
return "Name: " + name + "\r\n" +
"Capitol: " + capitol + "\r\n" +
"Largest City: " + largestCity + "\r\n" +
"State Bird: " + bird + "\r\n" +
"State Flower: " + flower;
}
}
}
======= Indexer.Indexer.Program.cs ===================================
using System;
using System.Collections;
namespace Indexer
{
///
/// Indexer Example: Show how to implement a custom indexer.
/// This example uses two overloaded indexers.
///
public class Program
{
public static void Main()
{
StateInfo x = new StateInfo("Illinois", "Springfield",
"Chicago", "Cardinal", "Purple Violet");
// Retrieve items by index.
for(int i = 0; i <= 4; i++)
Console.WriteLine(x[i]);
Console.WriteLine();
// Retrieve items by key.
Console.WriteLine(x["name"]);
Console.WriteLine(x["capitol"]);
Console.WriteLine(x["largestcity"]);
Console.WriteLine(x["bird"]);
Console.WriteLine(x["flower"]);
Console.WriteLine();
// Print items using ToString method.
Console.WriteLine(x);
Console.ReadLine();
}
}
}
// Console Output:
Illinois
Springfield
Chicago
Cardinal
Purple Violet
Illinois
Springfield
Chicago
Cardinal
Purple Violet
Name: Illinois
Capitol: Springfield
Largest City: Chicago
State Bird: Cardinal
State Flower: Purple Violet
------- Indexer.Indexer.StateInfo.cs ---------------------------------
using System;
using System.Collections;
namespace Indexer
{
///
/// Indexer Example: Show how to implement a custom indexer.
/// This example uses two overloaded indexers.
///
public class StateInfo
{
private string name, capitol, largestCity, bird, flower;
// Parameterized constructor.
public StateInfo(string theName, string theCapitol,
string theLargestCity, string theBird, string theFlower)
{
name = theName;
capitol = theCapitol;
largestCity = theLargestCity;
bird = theBird;
flower = theFlower;
}
// Indexer that works for numeric indices.
public string this[int index]
{
get
{
string returnValue;
switch (index)
{
case 0: returnValue = name; break;
case 1: returnValue = capitol; break;
case 2: returnValue = largestCity; break;
case 3: returnValue = bird; break;
case 4: returnValue = flower; break;
default: return "Illegal index.";
}
return returnValue;
}
}
// Indexer that works for numeric indices.
public string this[string key]
{
get
{
string returnValue;
switch (key)
{
case "name": returnValue = name; break;
case "capitol": returnValue = capitol; break;
case "largestcity":returnValue = largestCity; break;
case "bird": returnValue = bird; break;
case "flower": returnValue = flower; break;
default: return "Illegal index.";
}
return returnValue;
}
}
public override string ToString()
{
return "Name: " + name + "\r\n" +
"Capitol: " + capitol + "\r\n" +
"Largest City: " + largestCity + "\r\n" +
"State Bird: " + bird + "\r\n" +
"State Flower: " + flower;
}
}
}
=== CustomCollection.CustomCollection.Program.cs ============
using System;
using System.Collections;
namespace CustomCollection
{
///
/// CustomCollection Example: Create a custom collection by
/// implementing the IEnumerable interface, which requires the
/// GetEnumerator method.
///
public class Program
{
public static void Main()
{
StateInfo x = new StateInfo("Illinois", "Springfield",
"Chicago", "Cardinal", "Purple Violet");
IEnumerator i;
Console.WriteLine(x);
Console.WriteLine();
i = x.GetEnumerator();
// Enumerate objects explicitly.
while (i.MoveNext())
Console.WriteLine(i.Current);
Console.WriteLine();
// Enumerate objects using foreach statement.
foreach(object obj in x)
Console.WriteLine(obj);
Console.ReadLine();
}
}
}
// Console Output:
Name: Illinois
Capitol: Springfield
Largest City: Chicago
State Bird: Cardinal
State Flower: Purple Violet
Illinois
Springfield
Chicago
Cardinal
Purple Violet
Illinois
Springfield
Chicago
Cardinal
Purple Violet
--- CustomCollection.CustomCollection.StateInfo.cs ----------
using System;
using System.Collections;
namespace CustomCollection
{
///
/// CustomCollection Example: Create a custom collection by
/// implementing the IEnumerable interface, which requires the
/// GetEnumerator method.
///
public class StateInfo : IEnumerable
{
private string mvarName, mvarCapitol, mvarLargestCity,
mvarBird, mvarFlower;
public StateInfo(string n, string c, string lc, string b, string f)
{
mvarName = n;
mvarCapitol = c;
mvarLargestCity = lc;
mvarBird = b;
mvarFlower = f;
}
public string Name
{
get { return mvarName; }
}
public string Capitol
{
get { return mvarCapitol; }
}
public string LargestCity
{
get { return mvarLargestCity; }
}
public string Bird
{
get { return mvarBird; }
}
public string Flower
{
get { return mvarFlower; }
}
public override string ToString()
{
return "Name: " + Name + "\r\n" +
"Capitol: " + Capitol + "\r\n" +
"Largest City: " + LargestCity + "\r\n" +
"State Bird: " + Bird + "\r\n" +
"State Flower: " + Flower;
}
public IEnumerator GetEnumerator()
{
ArrayList col = new ArrayList();
col.Add(Name);
col.Add(Capitol);
col.Add(LargestCity);
col.Add(Bird);
col.Add(Flower);
return col.GetEnumerator();
}
}
}
=== CustomEnumerator.CustomEnumerator.Program.cs ============
using System;
using System.Collections;
namespace CustomEnumerator
{
///
/// CustomEnumerator Example: The Main method for this example
/// is the same as the CustomCollection Example.
///
public class Program
{
public static void Main()
{
StateInfo x = new StateInfo("Illinois", "Springfield",
"Chicago", "Cardinal", "Purple Violet");
IEnumerator i;
Console.WriteLine(x);
Console.WriteLine();
i = x.GetEnumerator();
// Enumerate objects explicitly.
while (i.MoveNext())
Console.WriteLine(i.Current);
Console.WriteLine();
// Enumerate objects using foreach statement.
foreach(object obj in x)
Console.WriteLine(obj);
Console.ReadLine();
}
}
}
// Console Output:
Name: Illinois
Capitol: Springfield
Largest City: Chicago
State Bird: Cardinal
State Flower: Purple Violet
Illinois
Springfield
Chicago
Cardinal
Purple Violet
Illinois
Springfield
Chicago
Cardinal
Purple Violet
--- CustomEnumerator.CustomEnumerator.StateInfo.cs ----------
using System;
using System.Collections;
using System.Text;
namespace CustomEnumerator
{
///
/// CustomEnumerator Example: StateInfo not only implements
/// IEnumerator, but IEnumerable as well, which means that
/// Current, Reset, and MoveNext must be supplied as well.
///
public class StateInfo : IEnumerator, IEnumerable
{
private string mvarName, mvarCapitol, mvarLargestCity,
mvarBird, mvarFlower;
private int mvarPos;
// Parameterized constructor.
public StateInfo(string n, string c, string lc, string b, string f)
{
mvarName = n;
mvarCapitol = c;
mvarLargestCity = lc;
mvarBird = b;
mvarFlower = f;
mvarPos = -1;
}
// Copy constructor.
public StateInfo(StateInfo s)
{
mvarName = s.mvarName;
mvarCapitol = s.mvarCapitol;
mvarLargestCity = s.mvarLargestCity;
mvarBird = s.mvarBird;
mvarFlower = s.mvarFlower;
mvarPos = -1;
}
public string Name
{
get { return mvarName; }
}
public string Capitol
{
get { return mvarCapitol; }
}
public string LargestCity
{
get { return mvarLargestCity; }
}
public string Bird
{
get { return mvarBird; }
}
public string Flower
{
get { return mvarFlower; }
}
public override string ToString()
{
return "Name: " + Name + "\r\n" +
"Capitol: " + Capitol + "\r\n" +
"Largest City: " + LargestCity + "\r\n" +
"State Bird: " + Bird + "\r\n" +
"State Flower: " + Flower;
}
public object Current
{
get
{
switch (mvarPos)
{
case 0: return Name;
case 1: return Capitol;
case 2: return LargestCity;
case 3: return Bird;
case 4: return Flower;
default: return "Bad Position Number.";
}
}
}
public void Reset()
{
mvarPos = -1;
}
public bool MoveNext()
{
if (-1 <= mvarPos && mvarPos < 4)
{
mvarPos += 1;
return true;
}
else
return false;
}
public IEnumerator GetEnumerator()
{
return new StateInfo(this);
}
}
}
======= CustomSerialization.CustomSerialization.SerializeOut.cs ======
using System;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
namespace CustomSerialization
{
///
/// CustomSerialization Example: For custom serialization
/// with a BinaryFormatter object, the class to be serialized
/// must implement the ISerializable interface, which requires
/// a noarg constructor and the GetObjectData and SerializationInfo
/// methods. The "custom part" is outputting the name in upper case.
///
public class SerializeOut
{
public static void Main()
{
string outputFile = "Persons.bin";
Person p = new Person("Sally", "F", 29);
BinaryFormatter bf = new BinaryFormatter();
Stream s = File.Create(outputFile);
bf.Serialize(s, p);
s.Close();
Console.WriteLine("Serialization finished.");
Console.ReadLine();
}
}
}
// Console Output:
Serialization finished.
------- CustomSerialization.CustomSerialization.SerializeIn.cs -------
using System;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
namespace CustomSerialization
{
///
/// CustomSerialization Example: For custom serialization
/// with a BinaryFormatter object, the class to be serialized
/// must implement the ISerializable interface, which requires
/// a noarg constructor and the GetObjectData and SerializationInfo
/// methods. The "custom part" is outputting the name in upper case.
///
public class SerializeIn
{
public static void Main()
{
string inputFile = "Persons.bin";
BinaryFormatter bf = new BinaryFormatter();
Stream s = File.OpenRead(inputFile);
Person p;
p = (Person) bf.Deserialize(s);
Console.WriteLine("Deserialization finished.");
Console.WriteLine(p);
Console.ReadLine();
}
}
}
// Console Output:
Deserialization finished.
SALLY F 29
------- CustomSerialization.CustomSerialization.Person.cs ------------
using System;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
namespace CustomSerialization
{
///
/// CustomSerialization Example: For custom serialization
/// with a BinaryFormatter object, the class to be serialized
/// must implement the ISerializable interface, which requires
/// a noarg constructor and the GetObjectData and SerializationInfo
/// methods. The "custom part" is outputting the name in upper case.
///
[Serializable()]
public class Person : ISerializable
{
public string name;
public string gender;
public int age;
public Person()
{
// Noarg constructor needed for compatibility.
}
public Person(string theName, string theGender, int theAge)
{
name = theName;
gender = theGender;
age = theAge;
}
public Person(SerializationInfo si, StreamingContext ctx)
{
name = si.GetString("NameInCaps");
gender = si.GetString("Gender");
age = si.GetInt32("Age");
}
public override string ToString()
{
return name + " " + gender + " " + age;
}
public virtual void GetObjectData(
SerializationInfo si, StreamingContext ctx)
{
si.AddValue("NameInCaps", name.ToUpper());
si.AddValue("Gender", gender);
si.AddValue("Age", age);
}
}
}
=== Unsafe.Unsafe.Program.cs ================================
using System;
namespace Unsafe
{
///
/// Unsafe Example:
/// (1) Perform pointer operations in
/// an unsafe block.
/// (2) Use an unchecked block to suppress checking
/// for overflow with integer types.
/// The unsafe keyword is required when working with
/// pointer types;
///
///
/// Before compiling this program set the build action
/// to allow unsafe code and check for integer overflow:
/// (1) Go to the project properties pages >> Build Tab >>
/// Check the Allow Unsafe Code checkbox.
/// (2) On the project properties pages >> Build Tab >>
/// Advanced Button >> Check for arithmetic
/// overflow/underflow >> OK.
///
public class Program
{
public static void Main()
{
// Create and print array in standard fashion.
int[] a = { 1, 3, 5, 7, 9 };
for (int i = 0; i <= 4; i++)
Console.Write(a[i] + " ");
Console.WriteLine();
// Pointer types can only be declared and used
// in a block marked as unsafe.
unsafe
{
// Create array directly from stack, not
// subject to garbage collection.
int* b = stackalloc int[5];
// Assign variables pointer style.
for (int i = 0; i <= 4; i++)
*(b + i) = 2 * i + 2;
// Print values of allocated memory area,
// Pointer Style 1:
for (int i = 0; i <= 4; i++)
Console.Write(*(b + i) + " ");
Console.WriteLine();
// Determine start and end of memory area.
// See what happens if 4 in following line
// is changed to 5 or larger value.
int* start = b;
int* end = b + 4;
// Print values of allocated memory area,
// Pointer Style 2:
for (int* p = start; p <= end; p++)
Console.Write(*p + " ");
Console.WriteLine("\n");
}
// Create new object on heap.
Vector r = new Vector(4, 5);
Console.WriteLine(r);
unsafe
{
// Pin r in place so it will not be moved or
// garbage collected.
fixed (int* s = &(r.x))
{
Console.WriteLine("{0} {1} {2}",
*s, *(s + 1), *(s + 2));
Console.WriteLine();
}
// Now r is free to be garbage collected.
}
unsafe
{
// Create new VectorS object on the stack.
VectorS t = new VectorS(5, 6);
Console.WriteLine(t);
// Defining an unsafe pointer to t.
VectorS* u = &t;
// Print x and y fields pointer style.
Console.WriteLine(u -> x + " " + u -> y);
Console.WriteLine();
}
// An unchecked block is one where arithmetic
// overflow in integer types is not performed.
// The default compiler setting is not to check
// for integer overflow.
unchecked
{
int x = 3;
for (int y = 1; y <= 10; y++)
{
Console.WriteLine(x);
x *= x;
}
}
Console.ReadLine();
}
}
}
// Console Output:
1 3 5 7 9
2 4 6 8 10
2 4 6 8 10
(4,5)
4 5 -2147483648
(5,6)
5 6
3
9
81
6561
43046721
-501334399
2038349057
-1970898431
120648705
1995565057
--- Unsafe.Unsafe.Vector.cs ---------------------------------
using System;
using System.Collections.Generic;
using System.Text;
namespace Unsafe
{
///
/// Unsafe Example: Vector class to use with pointer operations.
///
public class Vector
{
public int x, y;
public Vector(int theX, int theY)
{
x = theX;
y = theY;
}
public override string ToString()
{
return String.Format("({0},{1})", x, y);
}
}
}
--- Unsafe.Unsafe.VectorS.cs --------------------------------
using System;
using System.Collections.Generic;
using System.Text;
namespace Unsafe
{
///
/// Unsafe Example: Vector struct to use with pointer operations.
///
public struct VectorS
{
public int x, y;
public unsafe VectorS(int theX, int theY)
{
x = theX;
y = theY;
}
public override string ToString()
{
return String.Format("({0},{1})", x, y);
}
}
}
=============================================================