C#-2 Source Code Files
=== C#-2.Strings.Program.cs =================================
using System;
namespace Strings
{
///
/// Strings Example: Illustrate some string declaration
/// styles and string properties and methods.
///
public class Program
{
public static void Main()
{
string a = "wolf";
char[] b = {'f', 'o', 'x'};
string c = new string(b);
string d = new string('X', 10);
string e, f;
Console.WriteLine(a + " " + c + " " + d);
Console.WriteLine();
// Illustrate Length property and Substring method.
e = a + c + d;
Console.WriteLine(e + " " + e.Length + " " + e.Substring(2, 4));
// Format is a static method of the String class.
int x = 3956;
f = String.Format("{0}***{1}", a, x);
Console.WriteLine(f);
Console.WriteLine();
// Compare behavior of Equals, ReferenceEquals and ==.
char[] g = { 'w', 'o', 'l', 'f' };
string h = new string(g);
string i = a;
Console.WriteLine(a.Equals(h) + " " +
string.ReferenceEquals(a, h) + " " + (a == h));
Console.WriteLine(a.Equals(i) + " " +
string.ReferenceEquals(a, i) + " " + (a == i));
Console.ReadLine();
}
}
}
// Console Output:
wolf fox XXXXXXXXXX
wolffoxXXXXXXXXXX 17 lffo
wolf***3956
True False True
True True True
=== C#-2.SSBComparison.Program.cs ===========================
using System;
using System.Text;
namespace SSBComparison
{
///
/// SSBComparison Example: Performance comparison of
/// String vs. StringBuilder objects.
///
///
/// Recall that string objects are immutable but
/// StringBuilder objects are not.
///
public class Program
{
public static void Main()
{
string s = "";
// Set initial capacity of sb to 80000.
StringBuilder sb = new StringBuilder("", 80000);
int i;
Console.WriteLine("Beginning String Example ...");
for(i = 1; i <= 80000; i++)
s += "*";
Console.WriteLine("String Example Ended");
Console.WriteLine("Press any key to continue.");
Console.ReadLine();
Console.WriteLine("Beginning StringBuilder Example ...");
for(i = 1; i <= 80000; i++)
sb.Append("*");
s = sb.ToString();
Console.WriteLine("String BuilderExample Ended.");
Console.ReadLine();
}
}
}
// Console Output:
Beginning String Example ...
String Example Ended
Press any key to continue.
Beginning StringBuilder Example ...
String BuilderExample Ended.
=== C#-2.Vehicle1.Program.cs ================================
using System;
using System.Collections.Generic;
using System.Text;
namespace Vehicle1
{
public class Program
{
///
/// Vehicle1 Example: Implement properties as global
/// variables.
///
///
/// No constructor is defined, so a system default
/// constructor is supplied.
///
public static void Main()
{
Vehicle x = new Vehicle();
// Display uninitialized object.
x.display();
Console.WriteLine();
// Set properties in Vehicle x.
x.model = "Ford Taurus";
x.purchaseDate = new DateTime(2003, 5, 29);
x.miles = 1500;
// Display Vehicle object after initializing.
x.display();
// Print Vehicle object by invoking the
// ToString function.
Console.WriteLine(x);
Console.WriteLine();
// Add miles driven since last update.
x.addMiles(2000);
Console.WriteLine(x.miles);
Console.WriteLine();
// Create another Vehicle object.
Vehicle y = new Vehicle();
y.model = "Volkswagen Passat";
y.purchaseDate = new DateTime(2003, 9, 10);
y.miles = 9000;
Console.WriteLine(y);
Console.WriteLine();
// Change reference y to refer to x.
y = x;
x.addMiles(4000);
y.addMiles(3000);
Console.WriteLine(x);
Console.WriteLine(y);
Console.ReadLine();
}
}
}
// Console Output:
Model:
Purchase Date: 1
Miles: 0
Model: Ford Taurus
Purchase Date: 2003
Miles: 1500
Ford Taurus 2003 1500
3500
Volkswagen Passat 2003 9000
Ford Taurus 2003 10500
Ford Taurus 2003 10500
--- C#-2.Vehicle1.Vehicle.cs ---------------------------------
using System;
namespace Vehicle1
{
///
/// Vehicle1 Example: Implement properties as global
/// variables.
///
///
/// No constructor is defined, so a system default
/// constructor is supplied.
///
public class Vehicle
{
///
/// Make and model of vehicle.
///
public string model;
///
/// Purchase date of vehicle.
///
public DateTime purchaseDate;
///
/// Current odometer reading of vehicle.
///
public int miles;
///
/// Add specified number of months to original change date.
///
///
public void addMiles(int theMiles)
{
if (theMiles > 0)
miles += theMiles;
}
///
/// Displays object data.
///
public void display()
{
Console.WriteLine("Model: " + model);
Console.WriteLine("Purchase Date: " + purchaseDate.Year);
Console.WriteLine("Miles: " + miles);
}
///
/// Returns object data as a string.
///
public override string ToString()
{
return model + " " + purchaseDate.Year + " " + miles;
}
}
}
=== C#-2.Vehicle2.Program.cs ================================
using System;
namespace Vehicle2
{
public class Program
{
///
/// Vehicle2 Example: Uses Java-style getters and setters
/// to manipulate class data. The model and purchase date
/// are fixed by the constructor. Only the miles can be changed.
///
public static void Main()
{
Vehicle x = new Vehicle("Ford Taurus");
// Display uninitialized object.
Console.WriteLine(x.ToString());
Console.WriteLine();
// Set properties in Vehicle x.
x.setMiles(1500);
// Print Vehicle object by invoking the
// ToString function.
Console.WriteLine(x);
Console.WriteLine();
// Add miles driven since last update.
x.setMiles(2000);
Console.WriteLine(x.getModel());
Console.WriteLine(x.getYear());
Console.WriteLine(x.getMiles());
Console.WriteLine();
// Create another Vehicle object.
Vehicle y = new Vehicle("Volkswagen Passat",
new DateTime(2003, 9, 10), 9000);
Console.WriteLine(y);
Console.WriteLine();
// Change miles in x and y.
x.setMiles(1000);
y.setMiles(12000);
Console.WriteLine(x);
Console.WriteLine(y);
Console.ReadLine();
}
}
}
// Console Output:
Ford Taurus 2006 0
Ford Taurus 2006 1500
Ford Taurus
2006
2000
Volkswagen Passat 2003 9000
Ford Taurus 2006 2000
Volkswagen Passat 2003 12000
--- C#-2.Vehicle2.Vehicle.cs ---------------------------------
using System;
namespace Vehicle2
{
///
/// Vehicle2 Example: Uses Java-style getters and setters
/// to manipulate class data. The model and purchase date
/// are fixed by the constructor. Only the miles can be changed.
///
public class Vehicle
{
// Private member variables.
private string model;
private DateTime purchaseDate;
private int miles;
///
/// Noarg constructor.
///
public Vehicle(string theModel)
{
if (theModel != "")
model = theModel;
else
model = "Unknown";
purchaseDate = DateTime.Now;
miles = 0;
}
///
/// Parameterized constructor.
///
///
///
///
public Vehicle(string theModel,
DateTime thePurchaseDate, int theMiles)
{
if (theModel != "")
model = theModel;
else
model = "Unknown";
purchaseDate = thePurchaseDate;
if (theMiles >= 0)
miles = theMiles;
else
miles = 0;
}
///
/// Vehicle model.
///
public string getModel()
{
return model;
}
///
/// Year of vehicle.
///
public int getYear()
{
return purchaseDate.Year;
}
///
/// Miles on vehicle odometer.
///
public int getMiles()
{
return miles;
}
///
/// Update odometer miles only if new value
/// of miles is greater than original miles.
///
public void setMiles(int theMiles)
{
if (theMiles > miles)
miles = theMiles;
}
///
/// Returns object data as a string.
/// Overrides Object ToString method.
///
public override string ToString()
{
return model + " " + purchaseDate.Year + " " + miles;
}
}
}
=== C#-2.Vehicle3.Program.cs ================================
using System;
namespace Vehicle3
{
public class Program
{
///
/// Vehicle3 Example: Use .Net properties manipulate
/// class data. The model and purchase date are fixed
/// by the constructor. Only the miles can be changed.
///
public static void Main()
{
Vehicle x = new Vehicle("Ford Taurus");
// Display uninitialized object.
Console.WriteLine(x.ToString());
Console.WriteLine();
// Set properties in Vehicle x.
x.Miles = 1500;
// Print Vehicle object by invoking the
// ToString function.
Console.WriteLine(x);
Console.WriteLine();
// Add miles driven since last update.
x.Miles = 2000;
Console.WriteLine(x.Model);
Console.WriteLine(x.Year);
Console.WriteLine(x.Miles);
Console.WriteLine();
// Create another Vehicle object.
Vehicle y = new Vehicle("Volkswagen Passat",
new DateTime(2003, 9, 10), 9000);
Console.WriteLine(y);
Console.WriteLine();
// Change miles in x and y.
x.Miles = 1000;
y.Miles = 12000;
Console.WriteLine(x);
Console.WriteLine(y);
Console.ReadLine();
}
}
}
// Console Output:
Ford Taurus 2006 0
Ford Taurus 2006 1500
Ford Taurus
2006
2000
Volkswagen Passat 2003 9000
Ford Taurus 2006 2000
Volkswagen Passat 2003 12000
--- C#-2.Vehicle3.Vehicle.cs ---------------------------------
using System;
namespace Vehicle3
{
///
/// Uses Java-style getters and setters to manipulate class data.
/// The model and purchase date are fixed by the constructor.
/// Only the mile can be changed.
///
public class Vehicle
{
// Private member variables.
private string mvarModel;
private DateTime mvarPurchaseDate;
private int mvarMiles;
///
/// Noarg constructor.
///
public Vehicle(string theModel)
{
if (theModel != "")
mvarModel = theModel;
else
mvarModel = "Unknown";
mvarPurchaseDate = DateTime.Now;
mvarMiles = 0;
}
///
/// Parameterized constructor.
///
///
///
///
public Vehicle(string theModel,
DateTime thePurchaseDate, int theMiles)
{
if (theModel != "")
mvarModel = theModel;
else
mvarModel = "Unknown";
mvarPurchaseDate = thePurchaseDate;
if (theMiles >= 0)
mvarMiles = theMiles;
else
mvarMiles = 0;
}
///
/// Make and model of vehicle.
///
public string Model
{
get { return mvarModel; }
}
///
/// Year of vehicle.
///
public int Year
{
get { return mvarPurchaseDate.Year; }
}
///
/// Get or set odometer miles.
/// Set new value of miles only if new miles
/// is greater than original miles.
///
///
/// Miles on vehicle odometer.
///
public int Miles
{
get { return mvarMiles; }
set
{
if (value > mvarMiles)
mvarMiles = value;
}
}
///
/// Returns object data as a string.
/// Overrides Object ToString method.
///
public override string ToString()
{
return mvarModel + " " + mvarPurchaseDate.Year +
" " + mvarMiles;
}
}
}
=== C#-2.Vehicle4.Program.cs ================================
using System;
namespace Vehicle4
{
public class Program
{
///
/// Vehicle4 Example: Similar to Vehicle3 Example,
/// except that Vehicle is a struct instead of
/// a class. Check how the statement
/// y = x changes from the Vehicle1 example.
///
public static void Main()
{
Vehicle x = new Vehicle("Ford Taurus");
// Display uninitialized object.
Console.WriteLine(x.ToString());
Console.WriteLine();
// Set properties in Vehicle x.
x.Miles = 1500;
// Print Vehicle object by invoking the
// ToString function.
Console.WriteLine(x);
Console.WriteLine();
// Add miles driven since last update.
x.Miles = 2000;
Console.WriteLine(x.Model);
Console.WriteLine(x.Year);
Console.WriteLine(x.Miles);
Console.WriteLine();
// Create another Vehicle object.
Vehicle y = new Vehicle("Volkswagen Passat",
new DateTime(2003, 9, 10), 9000);
Console.WriteLine(y);
Console.WriteLine();
// Copy data from x into y.
y = x;
// Change miles in x and y.
x.Miles = 1000;
y.Miles = 12000;
Console.WriteLine(x);
Console.WriteLine(y);
Console.ReadLine();
}
}
}
// Console Output:
Ford Taurus 2006 0
Ford Taurus 2006 1500
Ford Taurus
2006
2000
Volkswagen Passat 2003 9000
Ford Taurus 2006 2000
Ford Taurus 2006 12000
--- C#-2.Vehicle4.Vehicle.cs ---------------------------------
using System;
namespace Vehicle4
{
///
/// Vehicle4 Example: Uses Java-style getters and setters
/// to manipulate class data. The model and purchase date
/// are fixed by the constructor. Only the miles can be changed.
///
public struct Vehicle
{
// Private member variables.
private string mvarModel;
private DateTime mvarPurchaseDate;
private int mvarMiles;
///
/// Noarg constructor.
///
public Vehicle(string theModel)
{
if (theModel != "")
mvarModel = theModel;
else
mvarModel = "Unknown";
mvarPurchaseDate = DateTime.Now;
mvarMiles = 0;
}
///
/// Parameterized constructor.
///
///
///
///
public Vehicle(string theModel,
DateTime thePurchaseDate, int theMiles)
{
if (theModel != "")
mvarModel = theModel;
else
mvarModel = "Unknown";
mvarPurchaseDate = thePurchaseDate;
if (theMiles >= 0)
mvarMiles = theMiles;
else
mvarMiles = 0;
}
///
/// Make and model of vehicle.
///
public string Model
{
get { return mvarModel; }
}
///
/// Year of vehicle.
///
public int Year
{
get { return mvarPurchaseDate.Year; }
}
///
/// Get or set odometer miles.
/// Set new value of miles only if new miles
/// is greater than original miles.
///
///
/// Miles on vehicle odometer.
///
public int Miles
{
get { return mvarMiles; }
set
{
if (value > mvarMiles)
mvarMiles = value;
}
}
///
/// Returns object data as a string.
/// Overrides Object ToString method.
///
public override string ToString()
{
return mvarModel + " " + mvarPurchaseDate.Year +
" " + mvarMiles;
}
}
}
=== C#-2.Vector1.Program.cs =================================
using System;
namespace Vector1
{
///
/// Vector1 Example: Illustrates calling one constructor
/// from another and how to define an Equals method
/// for a class.
///
public class Program
{
public static void Main()
{
// Declare the Vector reference variables.
Vector p, q, r, s, t;
// Create five Vector objects.
p = new Vector();
q = new Vector(3);
r = new Vector(2, 5);
s = new Vector(0, 0);
t = p;
// Output Vector objects.
Console.WriteLine(p + " " + q + " " + r + " " + s + " " + t);
// Test Equals method.
Console.WriteLine(p.Equals(s) + " " + p.Equals(r));
Console.WriteLine();
// Test GetHashCode method. Display output in hex (base 16).
Console.WriteLine(Convert.ToString(p.GetHashCode(), 16));
Console.ReadLine();
}
}
}
// Console Output:
(0,0) (3,3) (2,5) (0,0) (0,0)
True False
53c38023
--- C#-2.Vector1.Vector.cs ----------------------------------
using System;
using System.Collections.Generic;
using System.Text;
namespace Vector1
{
///
/// Vector1 Example: Illustrates calling one constructor
/// from another and how to define an Equals method
/// for a class.
///
public class Vector
{
///
/// x-coordinate of vector.
///
public int x;
///
/// y-coordinate of vector.
///
public int y;
///
/// Parameterized constructor with two parameters.
///
public Vector(int x, int y)
{
this.x = x;
this.y = y;
}
///
/// Noarg constructor. The constructor with
/// two parameters is invoked.
///
public Vector() : this(0, 0) { }
///
/// Parameterized constructor with one parameter.
/// The constructor with two parameters is invoked.
///
public Vector(int value) : this(value, value) { }
///
/// Overridden object ToString method.
///
/// Vector in ordered pair notation.
public override string ToString()
{
return "(" + x + "," + y + ")";
}
///
/// Two Vector objects are equal if their x and y
/// coordinates are respectively equal.
///
///
/// true if vectors are equal, false otherwise.
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();
}
}
}
=== C#-2.FileIO1.Program.cs =================================
using System;
using System.IO;
namespace FileIO1
{
///
/// FileI01 Example: Users StreamReader and StreamWriter
/// objects to read from and write to files, respectively.
///
///
/// Two methods are used to check for EOF: checking whether the
/// line read is equal to null and using the Peek method to
/// check the next unread character in the input buffer.
///
public class Program
{
public static void Main()
{
// Declare variables.
StreamReader sr1 = new StreamReader("numbers.txt");
StreamReader sr2 = new StreamReader("numbers.txt");
StreamWriter sw = new StreamWriter("average.txt");
string line;
int value, count = 0;
double sum = 0.0;
// Compute average using line != null to check for EOF.
line = sr1.ReadLine();
while (line != null)
{
value = int.Parse(line);
sum += value;
count++;
line = sr1.ReadLine();
}
sw.WriteLine("Average using sr1: " + sum / count);
Console.WriteLine("Average computed using sr1.");
// Compute average using Peek method to check for EOF.
sum = 0.0;
count = 0;
while (sr2.Peek() != -1)
{
line = sr2.ReadLine();
value = int.Parse(line);
sum += value;
count++;
}
sw.WriteLine("Average using sr2: " + sum / count);
// Flush buffer and close StreamWriter object.
sw.Close();
Console.WriteLine("Average computed using sr2.");
Console.ReadLine();
}
}
}
// Console Output:
Average computed using sr1.
Average computed using sr2.
// Input from file numbers.txt
54
34
67
65
53
// Output from file average.txt
Average using sr1: 54.6
Average using sr2: 54.6
=== C#-2.ArrayListCol.Program.cs ============================
using System;
using System.Collections;
namespace ArrayListCol
{
///
/// ArrayListCol Example: Adds, accesses and removes
/// items from an ArrayList collection.
///
///
/// Elements in an ArrayList collection are
/// referenced by zero-based index, just like a
/// traditional array.
///
public class Program
{
public static void Main()
{
ArrayList col = new ArrayList();
// Add items to collection col
col.Add(5);
col.Add("apple");
col.Add(true);
// Insert 17 before item at index 2.
col.Insert(2, 17);
// Print items in col using traditional For loop.
for(int i = 0; i < col.Count; i++)
Console.WriteLine(col[i]);
Console.WriteLine();
// Print items in col using foreach syntax.
foreach(Object obj in col)
Console.WriteLine(obj);
Console.WriteLine();
// Access item by index.
Console.WriteLine("Item 2 is " + col[2]);
Console.WriteLine("Count of col is " + col.Count);
col.RemoveAt(1);
Console.WriteLine("New count of col is " + col.Count);
Console.WriteLine();
// Print collection after removing item 1.
foreach(Object obj in col)
Console.WriteLine(obj);
Console.WriteLine();
Console.ReadLine();
}
}
}
// Console Output:
5
apple
17
True
5
apple
17
True
Item 2 is 17
Count of col is 4
New count of col is 3
5
17
True
=== C#-2.VehicleArray.Program.cs ============================
using System;
using System.IO;
namespace VehicleArray
{
///
/// VehicleArray Example: Creates and prints an array of
/// Vehicle objects. The data is obtained from the text file
/// vehicles.txt.
///
///
/// Copy the vehicles.txt file from the source code folder to
/// the bin/Debug folder before executing the application.
///
public class Program
{
public static void Main()
{
// Declare variables.
Vehicle[] x = new Vehicle[8];
String theModel;
int theYear, theMiles, i;
String inputFileName = "vehicles.txt", line;
// Create StreamReader object.
StreamReader inFile = new StreamReader(inputFileName);
// Create array of Vehicle objects from file data.
for(i = 0; inFile.Peek() != -1; i++)
{
line = inFile.ReadLine();
theModel = line.Substring(0, 19).Trim();
theYear = int.Parse(line.Substring(20, 4).Trim());
theMiles = int.Parse(line.Substring(25, 6).Trim());
x[i] = new Vehicle(theModel, theYear, theMiles);
}
// Print Vehicle array.
for(i = 0; i <= x.GetUpperBound(0); i++)
if (x[i] != null)
Console.WriteLine(x[i]);
else
Console.WriteLine("null");
Console.WriteLine();
// Print array item with index 3.
// (Invokes Vehicle.ToString method.)
Console.WriteLine(x[3]);
Console.ReadLine();
}
}
}
// Console Output:
Ford Taurus 2003 35000
Volkswagon Passat 2002 76000
Toyota Corolla 1996 97000
Nissan Sentra 1994 107000
Volkswagen Jetta 2002 12000
null
null
null
Nissan Sentra 1994 107000
--- C#-2.VehicleArray.Vehicle -------------------------------
using System;
namespace VehicleArray
{
///
/// VehicleArray Example: Creates and prints an array
/// of Vehicle objects. The data is obtained from
/// the text file vehicles.txt.
///
class Vehicle
{
private string mvarModel;
private int mvarYear;
private int mvarMiles;
public Vehicle(string theModel, int theYear, int theMiles)
{
mvarModel = theModel;
mvarYear = theYear;
if (theMiles >= 0)
mvarMiles = theMiles;
else
mvarMiles = 0;
}
public override string ToString()
{
return mvarModel + " " + mvarYear + " " + mvarMiles;
}
}
}
=== C#-2.VehicleCol.Program.cs ==============================
using System;
using System.Collections;
using System.IO;
namespace VehicleCol
{
///
/// VehicleCol Example: Creates, accesses and modifies an
/// ArrayList collection of Vehicle objects.
///
///
/// Copy the vehicle.csv file from the source code folder
/// to the bin/Debug folder before executing the application.
///
public class Program
{
public static void Main()
{
// Declare variables.
string theModel, line, inputFileName = "vehicles.csv";
string[] fields;
int theYear, theMiles;
Vehicle vehicle;
StreamReader inFile = new StreamReader(inputFileName);
ArrayList col = new ArrayList();
// Read data and create array of Vehicle objects.
while(inFile.Peek() > -1)
{
line = inFile.ReadLine();
fields = line.Split(',');
theModel = fields[0];
theYear = int.Parse(fields[1]);
theMiles = int.Parse(fields[2]);
col.Add(new Vehicle(theModel, theYear, theMiles));
}
// Print all vehicles in the collection.
foreach(Object obj in col)
Console.WriteLine(obj);
Console.WriteLine();
// Print vehicle with index 1.
Console.WriteLine(col[1]);
// Modify vehicle with index 1 in two ways.
// Way #1.
((Vehicle)col[1]).Miles = 86000;
Console.WriteLine(col[1]);
Console.WriteLine(col[1]);
// Way #2.
vehicle = (Vehicle)col[1];
vehicle.Miles = 88000;
Console.WriteLine(col[1]);
Console.ReadLine();
}
}
}
// Console Output:
Ford Taurus 2003 35000
Volkswagon Passat 2002 76000
Toyota Corolla 1996 97000
Volkswagon Passat 2002 76000
Volkswagon Passat 2002 86000
Volkswagon Passat 2002 86000
Volkswagon Passat 2002 88000
--- C#-2.VehicleCol.Vehicle.cs ------------------------------
using System;
namespace VehicleCol
{
///
/// VehicleCol Example: Creates and prints an ArrayList
/// collection of Vehicle objects. The data is obtained
/// from the text file vehicles.txt.
///
public class Vehicle
{
private string mvarModel;
private int mvarYear;
private int mvarMiles;
public Vehicle(string theModel, int theYear, int theMiles)
{
mvarModel = theModel;
mvarYear = theYear;
if (theMiles >= 0)
mvarMiles = theMiles;
else
mvarMiles = 0;
}
public int Miles
{
get { return mvarMiles; }
set { mvarMiles = value; }
}
public override string ToString()
{
return mvarModel + " " + mvarYear + " " + mvarMiles;
}
}
}
=== C#-2.Employee.Program.cs ================================
using System;
namespace Employee
{
///
/// Employee Example: Illustrates an inheritance hierarchy.
/// Tests the overloaded computeSalary, display,
/// and ToString methods.
///
public class Program
{
public static void Main()
{
Person x = new Person("Nancy", 'F', 29);
Console.WriteLine(">>> Person.display >>>");
x.display();
Console.WriteLine();
Console.WriteLine(">>> Person.ToString >>>");
Console.WriteLine(x);
Console.WriteLine();
Employee y = new Employee("Bill", 'M', 34, 34235, 95000);
Console.WriteLine(">>> Employee.display >>>");
y.display();
Console.WriteLine();
Console.WriteLine(">>> Employee.ToString >>>");
Console.WriteLine(y);
Console.WriteLine();
Executive z = new Executive("Charles", 'M', 34,
98373, 240000, 80000);
Console.WriteLine(">>> Executive.display >>>");
z.display();
Console.WriteLine();
Console.WriteLine(">>> Executive.ToString >>>");
Console.WriteLine(z);
Console.WriteLine();
Console.WriteLine(">>> Employee.computeSalary >>>");
Console.WriteLine(y.computeSalary());
Console.WriteLine();
Console.WriteLine(">>> Executive.computeSalary >>>");
Console.WriteLine(z.computeSalary());
Console.ReadLine();
}
}
}
// Console Output:
>>> Person.display >>>
Name = Nancy
Gender = F
Age = 29
>>> Person.ToString >>>
Nancy F 29
>>> Employee.display >>>
Name = Bill
Gender = M
Age = 34
ID = 34235
Salary = 95000
>>> Employee.ToString >>>
Bill M 34 34235 95000
>>> Executive.display >>>
Name = Charles
Gender = M
Age = 34
ID = 98373
Salary = 240000
Bonus = 80000
>>> Executive.ToString >>>
Charles M 34 98373 240000 80000
>>> Employee.computeSalary >>>
95000
>>> Executive.computeSalary >>>
320000
--- C#-2.Employee.Person.cs ---------------------------------
using System;
namespace Employee
{
///
/// Employee Example: Illustrates an inheritance hierarchy.
/// Tests the overloaded computeSalary, display,
/// and ToString methods.
///
public class Person
{
private string name;
private char gender;
private int age;
///
/// Parameterized Constructor
///
/// Name
/// Gender
/// Age
public Person(string n, char g, int a)
{
name = n;
gender = g;
age = a;
}
///
/// Display class fields to console.
///
public virtual void display()
{
Console.WriteLine("Name = " + name);
Console.WriteLine("Gender = " + gender);
Console.WriteLine("Age = " + age);
}
///
/// Override of object ToString method.
///
/// Concatenated class fields.
public override string ToString()
{
return name + " " + gender + " " + age;
}
}
}
--- C#-2.Employee.Employee.cs -------------------------------
using System;
namespace Employee
{
///
/// Employee Example: Illustrates an inheritance hierarchy.
/// Tests the overloaded computeSalary, display,
/// and ToString methods.
///
///
/// An Employee is a Person with an ID and salary.
///
public class Employee : Person
{
private int id;
protected double salary;
///
/// Parameterized Constructor
///
/// Name
/// Gender
/// Age
/// ID
/// Salary
public Employee(string n, char g, int a,
int i, double s) : base(n, g, a)
{
id = i;
salary = s;
}
///
/// Display class fields to console.
///
public override void display()
{
base.display();
Console.WriteLine("ID = " + id);
Console.WriteLine("Salary = " + salary);
}
///
/// Override of object ToString method.
///
/// Concatenated class fields.
///
public override string ToString()
{
return base.ToString() + " " + id + " " + salary;
}
///
/// Compute salary. No bonus is included for Employee.
///
///
/// Salary
///
public virtual double computeSalary()
{
return salary;
}
}
}
--- C#-2.Employee.Executive.cs ------------------------------
using System;
namespace Employee
{
///
/// Employee Example: Illustrates an inheritance hierarchy.
/// Tests the overloaded computeSalary, display,
/// and ToString methods.
///
///
/// An Executive is an Employee with a bonus.
///
public class Executive : Employee
{
private double bonus;
///
/// Parameterized constructor.
///
/// Name
/// Gender
/// Age
/// ID
/// Salary
/// Bonus
public Executive(string n, char g, int a,
int i, double s, double b) : base(n, g, a, i, s)
{
bonus = b;
}
///
/// Display class fields to console.
///
public override void display()
{
base.display();
Console.WriteLine("Bonus = " + bonus);
}
///
/// Override of object ToString method.
///
/// Concatenated class fields.
///
public override string ToString()
{
return base.ToString() + " " + bonus;
}
///
/// Compute salary. The bonus is included for Executive.
///
///
/// Salary
///
public override double computeSalary()
{
return salary + bonus;
}
}
}
=== C#-2.Virtual.Program.cs ==================================
using System;
using System.Collections.Generic;
using System.Text;
namespace Virtual
{
///
/// Virtual Example: Illustrates that overloaded
/// methods in C# are "virtual." The method called
/// depends on the object type, not the reference variable
/// type.
///
public class Program
{
public static void Main()
{
Person[] a = new Person[3];
int i;
a[0] = new Person("Scott", 'M', 40);
a[1] = new Employee("Robert", 'M', 32, 84732, 45000);
a[2] = new Executive("Maggie", 'F', 28, 76293,
198000, 40000);
for (i = 0; i <= a.GetUpperBound(0); i++)
{
a[i].display();
Console.WriteLine();
}
Console.ReadLine();
}
}
}
// Console Output:
Name = Scott
Gender = M
Age = 40
Name = Robert
Gender = M
Age = 32
ID = 84732
Salary = 45000
Name = Maggie
Gender = F
Age = 28
ID = 76293
Salary = 198000
Bonus = 40000
--- C#-2.Virtual.Person.cs -----------------------------------
Same as in Employee Example above.
--- C#-2.Virtual.Employee.cs -----------------------------------
Same as in Employee Example above.
--- C#-2.Virtual.Executive.cs -----------------------------------
Same as in Employee Example above.
=== C#-2.Abstract.Program.cs ====================================
using System;
namespace Abstract
{
///
/// Abstract Example: Shows the syntax of an abstract class
/// and method.
///
public class Program
{
public static void Main()
{
Child x = new Child();
x.F();
x.G();
Console.ReadLine();
}
}
}
// Console Output:
In method Parent.F
In method Child.G
--- C#-2.Parent.Parent.cs ------------------------------------
using System;
namespace Abstract
{
///
/// Abstract Example: Shows the syntax of an abstract class
/// and method.
///
public abstract class Parent
{
public void F()
{
Console.WriteLine("In method Parent.F");
}
public abstract void G();
}
}
--- C#-2.Parent.Child.cs -------------------------------------
using System;
namespace Abstract
{
///
/// Abstract Example: Shows the syntax of an abstract class
/// and method.
///
public class Child : Parent
{
public override void G()
{
Console.WriteLine("In method Child.G");
}
}
}
=== C#-2.Virtual.Program.cs ==================================
using System;
using System.ComponentModel;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Windows.Forms;
namespace Brushes
{
///
/// Brushes Example: Show the effect of using these brushes:
/// HatchBrush, LinearGradientBrush, SolidBrush, TextureBrush.
/// Note that Brush is an abstract class.
///
public partial class Form1 : Form
{
private Brush brush;
public Form1()
{
InitializeComponent();
}
private void Form1_Paint(object sender, PaintEventArgs e)
{
Rectangle r = new Rectangle(15, 15, ClientSize.Width - 30,
ClientSize.Height - 30);
e.Graphics.FillRectangle(brush, r);
}
private void Form1_Load(object sender, EventArgs e)
{
brush = new SolidBrush(Color.White);
}
private void mnuHatch_Click(object sender, EventArgs e)
{
brush = new HatchBrush(HatchStyle.ZigZag,
Color.DarkOrchid, Color.Beige);
this.Invalidate();
}
private void mnuLinearGradient_Click(object sender, EventArgs e)
{
brush = new LinearGradientBrush(new Point(15, 15),
new Point(ClientSize.Width - 20, ClientSize.Width - 20),
Color.Blue, Color.Red);
this.Invalidate();
}
private void mnuSolid_Click(object sender, EventArgs e)
{
brush = new SolidBrush(Color.MediumTurquoise);
this.Invalidate();
}
private void mnuTextured_Click(object sender, EventArgs e)
{
brush = new TextureBrush(Image.FromFile("../../Pizza.jpg"));
this.Invalidate();
}
}
}
=== C#-2.TryCatch.Program.cs =================================
// Console Output, Run #1:
Enter the dividend: 6
Enter the divisor: 3
6 / 3 = 2
The finally clause is always executed.
// Console Output, Run #2:
Enter the dividend: 6
Enter the divisor: 0
Division by Zero.
System.DivideByZeroException: Attempted to divide by zero.
at TryCatch.Program.Main() in
C:\Classes\0ndp-Fall-06\cs2-TextFile\cs2-ToRun\
TryCatch\TryCatch\Program.cs:line 24
The finally clause is always executed.
// Console Output, Run #3:
Enter the dividend: R
Enter the divisor: 8
Nonnumeric Input.
System.FormatException: Input string was not in a correct format.
at System.Number.StringToNumber(String str,
NumberStyles options, NumberBuffer& number,
NumberFormatInfo info, Boolean parseDecimal) at
System.Number.ParseInt32(String s, NumberStyles style,
NumberFormatInfo info)
at System.Int32.Parse(String s)
at TryCatch.Program.Main() in
C:\Classes\0ndp-Fall-06\cs2-TextFile\cs2-ToRun\
TryCatch\TryCatch\Program.cs:line 22
The finally clause is always executed.
==============================================================