Wednesday, July 27, 2011

Wednesday, 7/27/2011


using System;
using System.Collections.Generic;
using System.Text;

namespace ListCollection
{
//a simple class to store in the list
public class Employee
{
public Employee(int empID)
{
this.EmpID = empID;
}
public override string ToString()
{
return EmpID.ToString();
}
public int EmpID { get; set; }
}

public class Tester
{
static void Main()
{
//with an Array class, you define how many objects the array will hold
//with a list, you don't declare hwo many objects the List will hold
List empList = new List();
List intList = new List();

//populate the List
for (int i = 0; i < 5; i++)
{
empList.Add(new Employee(i+20));
intList.Add(i*3);
}

//print all the contents
for (int i = 0; i < intList.Count; i++)
{
Console.Write("{0} ", intList[i].ToString());
}

Console.WriteLine("\n");

//print all the contents of the Employee List
for (int i = 0; i < empList.Count; i++)
{
Console.Write("{0} ", empList[i].ToString());
}

Console.WriteLine("\n");
Console.WriteLine("empList.Capacity: {0}", empList.Capacity);
}
}
}




//the current Employee object must compare itself ot the Employee [assed in as a parameter
//and return -1 if it is smaller than the parameter, 1 if it is greater than the parameter
//and 0 if it is equal to the paramter

using System;
using System.Collections.Generic;
using System.Text;

namespace IComparable
{
//a simple class to store in the array
public class Employee : IComparable
{
private int empID;

public Employee(int empID)
{
this.empID = empID;
}

public override string ToString()
{
string str = "EmpID " + empID.ToString();
return str;
}

public bool Equals(Employee other)
{
if (this.empID == other.empID)
{
return true;
}
else
{
return false;
}
}

//comparer delegates back to Employee
//Employee uses the integer's default
//CompareTo method

public int CompareTo(Employee rhs)
{
return this.empID.CompareTo(rhs.empID);
}
}

public class Tester
{
static void Main()
{
List empArray = new List();
List intArray = new List();
//generate random numbers for
//both the integers and the employee IDs

Random r = new Random();

//populate the array
for (int i = 0; i < 5; i++)
{
//add a random employee id
empArray.Add(new Employee(r.Next(10) + 200));
//add a random integer
intArray.Add(r.Next(10));
}

//display all the contents of the int array
for (int i = 0; i < intArray.Count; i++)
{
Console.Write("{0} ", intArray[i].ToString());
}

Console.WriteLine("\n");

//display all the contents of the Employee array
for (int i = 0; i < empArray.Count; i++)
{
Console.Write("{0} ", empArray[i].ToString());
}

Console.WriteLine("\n");

//sort and display the int array
intArray.Sort();
for (int i = 0; i < intArray.Count; i++)
{
Console.Write("{0} ", intArray[i].ToString());
}
Console.WriteLine("\n");

//sort and display the employee array
empArray.Sort();

//display all the contents of the Employee array
for (int i = 0; i < empArray.Count; i++)
{
Console.Write("{0} ", empArray[i].ToString());
}
Console.WriteLine("\n");
}
}
}




using System;

class MainClass
{
public static void Main()
{
//all implicit
sbyte v = 55;
short v2 = v;
int v3 = v2;
long v4 = v3;

Console.WriteLine(v);
Console.WriteLine(v2);
Console.WriteLine(v3);
Console.WriteLine(v4);


//explicit to "smaller" types
v3 = (int)v4;
v2 = (short)v3;
v = (sbyte)v2;
Console.WriteLine(v);
Console.WriteLine(v2);
Console.WriteLine(v3);
}
}




using System;

class Example{
//void means that the method does not have to have a return type
public static void Main(){
//returns the boolean response
Console.WriteLine("10 > 9 is " + (10 > 9));
}
}




using System;

class Example
{
public static void Main()
{
bool b;

b = false;
Console.WriteLine("b is " + b);
b = true;
Console.WriteLine("b is " + b);

//a bool value can control the if statement
if (b)
{
Console.WriteLine("This is executed.");
}
b = false;
if (b)
{
Console.WriteLine("This is not executed.");
}
}
}




using System;
using System.Globalization;
public class Example
{
public static void Main()
{
CultureInfo[] cultures = {
CultureInfo.CreateSpecificCulture("en-US"),
CultureInfo.CreateSpecificCulture("fr-FR"),
CultureInfo.CreateSpecificCulture("es-ES")};
sbyte positiveNumber = 1;
sbyte negativeNumber = -5;
string[] specifiers = { "G", "C", "D4", "E2", "F", "N", "P", "X2" };

foreach (string specifier in specifiers)
{
foreach (CultureInfo culture in cultures)
{
Console.WriteLine("{0,2} format using {1} culture:{2,16} {3,16}",
specifier,
culture.Name,
positiveNumber.ToString(specifier, culture),
negativeNumber.ToString(specifier, culture));
}
}
}
}





using System;

class MainClass
{
public static void Main()
{
int[] intArray = new int[10];
int arrayLength = intArray.Length;
//total length of array;
Console.WriteLine("arrayLength = " + arrayLength);
for (int counter = 0; counter < arrayLength; counter++)
{
intArray[counter] = counter + 1;
Console.WriteLine("intArray[" + counter + "] = " + intArray[counter]);
}
}
}




using System;

class MainClass
{
public static void Main()
{
Console.WriteLine(5.ToString());
}
}




using System;

class MainClass
{
public static void Main()
{
int v = 55;
object o = v; //box v into o
Console.WriteLine("Value is {0}", o);
int v2 = (int)o;
Console.WriteLine(v2.ToString());
}
}

Tuesday, July 26, 2011

Tuesday 7/26/11


using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;

namespace Enumberable
{
public class ListBoxTest : IEnumerable
{
private string[] strings;
private int ctr = 0;
//enumberable classes can return an enumerator
public IEnumerator GetEnumerator()
{
foreach (string s in strings)
{
yield return s;
}
}

//explicit interface implementation.
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}

//initialize the listbox with strings
public ListBoxTest(params string[] initialStrings)
{
//allocate space for the strings
strings = new String[10];
//copy the string passed in to the constructor
foreach (string s in initialStrings)
{
strings[ctr++] = s;
}
}

//add a single string to the end of the listbox
public void Add(string theString)
{
strings[ctr] = theString;
ctr++;
}

//allow array-like access
public string this[int index]
{
get
{
if (index < 0 || index >= strings.Length)
{
//handle bad index
}
return strings[index];
}
set
{
strings[index] = value;
}
}

//publish how many strings you hold
public int GetNumEntries()
{
return ctr;
}
}

public class Tester
{
static void Main()
{
//create a new listbox and initialize
ListBoxTest lbt = new ListBoxTest("Howdy", "World");

//add a few strings
lbt.Add("Who");
lbt.Add("Is");
lbt.Add("Douglas");
lbt.Add("Adams");

//test the access
string subst = "Universe";
lbt[1] = subst;
;
//accesss all the strings
foreach (string s in lbt)
{
if (s != null)
{
Console.WriteLine("Value: {0}", s);
}
else
{
Console.WriteLine("Value: Null");
}
}
}
}
}




using System;
using System.Collections.Generic;
using System.Linq;

class Program
{
static void Main()
{
var worldCup2006Finalists = new[]{new
{
TeamName = "France",
Players = new string[]
{
"A", "B","C", "D",
}
},
new
{
TeamName = "Italy",
Players = new string[]
{
"Q", "W","E", "R",
}
}
};
Print(worldCup2006Finalists);
}

private static void Print(IEnumerable items)
{
foreach (T item in items)
{
Console.WriteLine(item);
}
}
}




using System;

class RefTest
{
public void sqr(ref int i)
{
i = i * i;
}
}

class MainClass
{
public static void Main()
{
RefTest ob = new RefTest();
int a = 10;
Console.WriteLine("a before call: " + a);
ob.sqr(ref a);
Console.WriteLine("a after call: " + a);
}
}

Monday, July 25, 2011

Monday 7/25/11


using System;
using System.Collections.Generic;
using System.Text;

namespace UsingParams
{
public class Tester
{
static void Main()
{
Tester t = new Tester();
//passes numbers
t.DisplayVals(5, 6, 7, 8);
int[] explicitArray = new int[6] { 1, 2, 3, 4, 5, 6 };
//passes array
t.DisplayVals(explicitArray);
}

public void DisplayVals(params int[] intVals)
{
foreach (int i in intVals)
{
Console.WriteLine("DisplayVals {0}", i);
}
}
}
}




using System;
using System.Collections.Generic;
using System.Text;

namespace RectangularArray
{
public class Tester
{
static void Main()
{
const int rows = 5;
const int columns = 3;

//declare a 4x3 integer array
int[,] rectangularArray = new int[rows, columns];

//populate the array
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < columns; j++)
{
rectangularArray[i, j] = i + j;
}
} // end populate

// report the contents of the array
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < columns; j++)
{
Console.Write(" rectangularArray[{0},{1}] = {2} ", i, j, rectangularArray[i, j]);
}
Console.WriteLine("");
}
}
} // end class Tester
} //end namespace




using System;
using System.Collections.Generic;
using System.Text;

namespace InitializingMultiDimensionalArray
{
public class Tester
{
static void Main()
{
const int rows = 4;
const int columns = 3;

//imply a 4X3 array
int[,] rectangularArray =
{
{0,1,2}, {3,4,5}, {6,7,8}, {9,10,11}
};

for (int i = 0; i < rows; i++)
{
for (int j = 0; j < columns; j++)
{
Console.WriteLine("rectangularArray[{0},{1}] = {2}", i, j, rectangularArray[i, j]);
}
}
}
}
}




using System;
using System.Collections.Generic;
using System.Text;


//a jagged array is an array of arrays
namespace JaggedArray
{
public class Tester
{
static void Main()
{
const int rows = 4;

//declare the jagged array as 4 rows high
//notice that the second dimension is not specified
int[][] jaggedArray = new int[rows][];

//the first row has five elements
jaggedArray[0] = new int[5];

//a row with 2 elements
jaggedArray[1] = new int[2];

//a row with 3 elements
jaggedArray[2] = new int[3];

//the last row has 5 elements
jaggedArray[3] = new int[5];

//fill some (but not all) elements of the rows
jaggedArray[0][3] = 15;
jaggedArray[1][1] = 12;
jaggedArray[2][1] = 9;
jaggedArray[2][2] = 145;
jaggedArray[3][0] = 10;
jaggedArray[3][1] = 14;
jaggedArray[3][2] = 15;
jaggedArray[3][3] = 15993;
jaggedArray[3][4] = 15;

for (int i = 0; i < 5; i++)
{
Console.WriteLine("jaggedArray[0][{0}] = {1}", i, jaggedArray[0][i]);
}

for (int i = 0; i < 2; i++)
{
Console.WriteLine("jaggedArray[1][{0}] = {1}", i, jaggedArray[1][i]);
}

for (int i = 0; i < 3; i++)
{
Console.WriteLine("jaggedArray[2][{0}] = {1}", i, jaggedArray[2][i]);
}

for (int i = 0; i < 5; i++)
{
Console.WriteLine("jaggedArray[3][{0}] = {1}", i, jaggedArray[3][i]);
}
}
}
}




using System;
using System.Collections.Generic;
using System.Text;

namespace SettingArrayBounds
{
public class SettingArrayBounds
{
public static void CreateArrayWithBounds()
{
//creates and initializes a multidimensional array of type string
int[] lengthsArray = new int[2] {3,5};
int[] boundsArray = new int[2] {2,3};
Array multiDimensionalArray = Array.CreateInstance(typeof(String), lengthsArray, boundsArray);

//displays the lower bounds and the upper bounds of each dimension
Console.WriteLine("Bounds:\tLower\tUpper");
for(int i = 0; i < multiDimensionalArray.Rank; i++)
{
Console.WriteLine("{0}:\t{1}\t{2}", i, multiDimensionalArray.GetLowerBound(i), multiDimensionalArray.GetUpperBound(i));
}
}
static void Main()
{
SettingArrayBounds.CreateArrayWithBounds();
}
}
}




using System;

class MainClass
{
public static void Main() {

int ivar;
double dvar;

ivar = 100;
dvar = 100.0;

Console.WriteLine("original value of ivar: " + ivar);
Console.WriteLine("original value of dvar: " + dvar);

Console.WriteLine();

//now divide both by 3

ivar = ivar / 3;
dvar = dvar / 3.0;

Console.WriteLine("ivar after division: " + ivar);
Console.WriteLine("dvar after division: " + dvar);
}
}




using System;

class MainClass
{
public static void Main()
{
uint value1 = 312;
byte value2 = (byte)value1;
Console.WriteLine("value2: {0}", value2);
}
}




namespace CompanyName
{
namespace UserInterface // nested namespace
{
public class MyClass
{
public void Test()
{
System.Console.WriteLine("userInterface Test()");
}
}
}
}

namespace CompanyName.DBAccess // nested namespace using dot
{
public class MyClass
{
public void Test()
{
System.Console.WriteLine("DatabaseAccess Test()");

}
}
}

class MainClass
{
public static void Main()
{
CompanyName.UserInterface.MyClass myUI = new CompanyName.UserInterface.MyClass();

CompanyName.DBAccess.MyClass myDB = new CompanyName.DBAccess.MyClass();

CompanyName.DBAccess.MyClass myMT = new CompanyName.DBAccess.MyClass();

myUI.Test();
myDB.Test();
myMT.Test();
}
}





using System;
using System.Collections.Generic;
using System.Text;

namespace ConvertingArrays
{
//create an object we can store in the array
public class Employee
{
//a simple class to store in the array
public Employee(int empID)
{
this.empID = empID;
}

public override string ToString()
{
string rs = empID.ToString() + " emp. ID";
return rs;
}
private int empID;
}

//This method take an array of objects. We'll pass in an array of Employees and then an array of strings.
//The conversion is implicit since both Employee and string derive (ultimately) from object.
public class Tester
{

public static void PrintArray(object[] theArray)
{
Console.WriteLine("Contents of the Array {0}", theArray.ToString());
//Walk through the array and print the values
foreach (object obj in theArray)
{
Console.WriteLine("Value: {0}", obj);
}
} //end printArray

static void Main()
{
//make an array of Employee objects
Employee[] myEmployeeArray = new Employee[5];
//initialize each Employee's value
for (int i = 0; i < 5; i++)
{
myEmployeeArray[i] = new Employee(i + 5);
}

//display the values
PrintArray(myEmployeeArray);

//create an array of two strings
string[] array = { "hello", "word" };

//print the value of the strings
PrintArray(array);
}
}
}




using System;
using System.Collections.Generic;
using System.Text;

namespace ArraySortAndRevers
{
public class Tester
{
public static void PrintMyArray(object[] theArray)
{
foreach (object obj in theArray)
{
Console.WriteLine("Value: {0}", obj);
}
Console.WriteLine("\n");
}

static void Main()
{
string[] myArray = { "Who", "is", "Douglas", "Adams" };

PrintMyArray(myArray);
Array.Reverse(myArray);
PrintMyArray(myArray);

String[] myOtherArray =
{
"We", "Hold", "These", "Truths", "To", "Be", "Self", "Evident"
};

PrintMyArray(myOtherArray);
//sorts alphabetically
Array.Sort(myOtherArray);
PrintMyArray(myOtherArray);
}
}
}




using System;
using System.Collections.Generic;
using System.Text;

namespace SimpleIndexer
{
//a simplified ListBox control
public class ListBoxTest
{
private string[] strings;
private int ctr = 0;

//initialize the listbox with strings
public ListBoxTest(params string[] initialStrings)
{
//allocate space for the strings
strings = new String[256];

//copy the strings passed in to the constructor
foreach (string s in initialStrings)
{
strings[ctr++] = s;
}
}

//add a single string ot the end fo the listbox
public void Add(string theString)
{
if (ctr >= strings.Length)
{
//handle bad index
}
else
{
strings[ctr++] = theString;
}
}

//allow array-like access

public string this[int index]
{
get
{
if (index < 0 || index >= strings.Length)
{
//handle bad index
}
return strings[index];
}
set
{
//add only through the add method
if (index >= ctr)
{
//handle errors
}
else
{
strings[index] = value;
}
}
}

//publish how many strings you hold
public int GetNumEntries()
{
return ctr;
}
}

public class Tester
{
static void Main()
{
//create a new listbox and initialize
ListBoxTest lbt = new ListBoxTest("Hello", "World");

//add a few strings
lbt.Add("Who");
lbt.Add("Is");
lbt.Add("Douglas");
lbt.Add("Adams");

//test the access
string subst = "Universe";
lbt[1] = subst;

Console.WriteLine(lbt.GetNumEntries());
//access all the strings
for (int i = 0; i < lbt.GetNumEntries(); i++)
{
Console.WriteLine("lbt[{0}]: {1}", i, lbt[i]);
}
}
}
}




using System;
using System.Collections.Generic;
using System.Text;

namespace OverloadedIndexer
{
//a simplified ListBoxTest
public class ListBoxTest
{
private string[] strings;
private int ctr = 0;

//initialize the listbox with strings
public ListBoxTest(params string[] initialStrings)
{
//allocate space for the strings
strings = new String[256];
//copy the strings passed in to the constructor
foreach (string s in initialStrings)
{
strings[ctr++] = s;
}
}

//add a single string to the end of the listbox
public void Add(string theString)
{
strings[ctr] = theString;
ctr++;
}

//allow array-like access
public string this[int index]
{
get
{
if (index < 0 || index >= strings.Length)
{
//handle bad index
}
return strings[index];
}
set
{
strings[index] = value;
}
}

private int findString(string searchString)
{
for (int i = 0; i < strings.Length; i++)
{
if (strings[i].StartsWith(searchString))
{
return i;
}
}
return -1;
}

//index on string
public string this[string index]
{
get
{
if (index.Length == 0)
{
//handle bad index
}

return this[findString(index)];
}
set
{
strings[findString(index)] = value;
}
}

//publish how many strings you hold
public int GetNumEntries()
{
return ctr;
}
}

public class Tester
{
static void Main()
{
//create a new listbox and initialize
ListBoxTest lbt = new ListBoxTest("Hello", "World");

//add a few strings
lbt.Add("Who");
lbt.Add("Is");
lbt.Add("Douglas");
lbt.Add("Adams");

//test the access
string subst = "Universe";
lbt[1] = subst;
lbt["Hel"] = "GoodBye";
//access al the strings
for (int i = 0; i < lbt.GetNumEntries(); i++)
{
Console.WriteLine("lbt[{0}]:{1}", i, lbt[i]);
}//end for
}//end main
}
}




<?php
$anemail = "lee@babinplanet.ca";
$thetoken = strtok($anemail, "@");
while($thetoken){
echo $thetoken . "
";
$thetoken = strtok("@");
}
?>





<?php
$astring = "Hello World";
echo strrev($astring);
?>


<?php
//the value passed to use by a customer who is signing up
$submittedpass = "myPass";
//before we insert into the dtabase, we simply lowercase teh submittal.
$newpass = strtolower($submittedpass);

echo $newpass;
?>





<?php
$astring = "hello world";
echo ucfirst($astring);
echo "
";
echo ucwords($astring);
?>




<div style = "padding:4px; line-height:1.3; color:blue; font-family: consolas, arial;">
$blankspaceallaround = "somepassword";
//this would result in all blank spaces being removed.
echo trim($blankspaceallaround) . "
";
//this would result in only the blank space at the beginning being trimmed
echo ltrim($blankspaceallaround) . "
";
//and as you can imagine, only the blank space at the end would be trimmed here
echo rtrim($blankspaceallaround) . "
";
?>

Friday, July 22, 2011

Friday 7/22/2011


using System;

namespace SimpleInterface
{
interface IStorable
{
//no access modifiers, methods are public
//no implementation
void Read();
void Write(object obj);
//notice that the property declaration doesn't provide an implementation for get and set, but simply designates that there is a get and set
//Interface methods are implicitly public beacuse an interface is a contract meant to be used by other classees
int Status { get; set; }
}

//create a class which implements the IStorable interface
public class Document : IStorable
{
public Document(string s)
{
Console.WriteLine("Creating document with: {0}", s);
}

//implement the Read method
public void Read()
{
Console.WriteLine("Implementing the Read Method for IStorable");
}

//implement the Write method
public void Write(object o)
{
Console.WriteLine("Implementing the Write Method for IStorable");
}

public int Status { get; set; }
}

//Take our interface out for a spin

public class Tester
{
static void Main()
{
//access the methods in the Document object
Document doc = new Document("Test Document");
doc.Status = -1;
doc.Read();
Console.WriteLine("Document Status: {0}", doc.Status);
}
}
}




using System;

namespace ExtendAndCombineInterface
{
interface IStorable
{
void Read();
void Write(object obj);
int Status { get; set; }
}

//here's the new interface
interface ICompressible
{
void Compress();
void Decompress();
}

//extend the interface
interface ILoggedCompressible : ICompressible
{
void LogSavedBytes();
}

//Combine Interfaces
interface IStorableCompressible : IStorable, ILoggedCompressible
{
void LogOriginalSize();
}

//yet another interface
interface IEncryptable
{
void Encrypt();
void Decrypt();
}

public class Document : IStorableCompressible, IEncryptable
{
//hold the data for IStorable's Status property
private int status = 0;
//the document constructor
public Document(string s)
{
Console.WriteLine("Creating the document with: {0}", s);
}

//implement IStorable
public void Read()
{
Console.WriteLine("Implementing the Read Method for IStorable");
}

public void Write(object o)
{
Console.WriteLine("Implementing the Write Method for IStorable");
}

public int Status { get; set; }

//implement ICompressible
public void Compress()
{
Console.WriteLine("Implementing Compress");
}


public void Decompress()
{
Console.WriteLine("Implementing Decompress");
}

//implement ILoggedCompressible
public void LogSavedBytes()
{
Console.WriteLine("Implementing LogSavedBytes");
}

//implement IStorableCompressible
public void LogOriginalSize()
{
Console.WriteLine("Implementing LogOriginalSize");
}

//implement IEncrytable
public void Encrypt()
{
Console.WriteLine("Implementing Encrypt");
}

public void Decrypt()
{
Console.WriteLine("Implementing Decrypt");
}
}

public class Tester
{
static void Main()
{
//create a document object
Document doc = new Document("Test Document");
doc.Read();
doc.Compress();
doc.LogSavedBytes();
doc.Compress();
doc.LogOriginalSize();
doc.Compress();
doc.Read();
doc.Encrypt();
}
}
}




using System;

namespace ExtendAndCombineInterface
{
interface IStorable
{
void Read();
void Write(object obj);
int Status{get;set;}
}

//here's the new interface
interface ICompressible
{
void Compress();
void Decompress();
}

//Extend the interface
interface ILoggedCompressible : ICompressible
{
void LogSavedBytes();
}

//Combines Interfaces
interface IStorableCompressible : IStorable, ILoggedCompressible
{
void LogOriginalSize();
}

//yet another interface
interface IEncryptable
{
void Encrypt();
void Decrypt();
}

public abstract class Document{}

public class BigDocument : Document, IStorableCompressible, IEncryptable
{
//hold the data for IStorable's Status property
private int status = 0;

//the document constructor
public BigDocument(string s)
{
Console.WriteLine("Creating the document with {0}", s);
}

//implement IStorable
public void Read()
{
Console.WriteLine("Implementing the Read Method for IStorable");
}

public void Write(object o)
{
Console.WriteLine("Implementing the Write Method for IStorable");
}

public int Status{get;set;}

//implement ICompressible
public void Compress()
{
Console.WriteLine("Implementing Compress");
}

public void Decompress()
{
Console.WriteLine("Implementing Decompress");
}

//implement ILoggedCompressible
public void LogSavedBytes()
{
Console.WriteLine("Implementing LogSavedBytes");
}


//implement IStorableCompressible
public void LogOriginalSize()
{
Console.WriteLine("Implementing LogOriginalSize");
}

//implement IEncryptable
public void Encrypt()
{
Console.WriteLine("Implementing Encrypt");
}

public void Decrypt()
{
Console.WriteLine("Implementing Decrypt");
}
}

class LittleDocument : Document, IEncryptable
{
public LittleDocument(string s)
{
Console.WriteLine("Creating document with: {0}", s);
}

void IEncryptable.Encrypt()
{
Console.WriteLine("Implementing Encrypt");
}

void IEncryptable.Decrypt()
{
Console.WriteLine("Implementing Decrypt");
}
}

public class Tester
{
static void Main()
{
Document[] folder = new Document[5];
for(int i = 0; i < 5; i++)
{
if(i % 2 == 0)
{
folder[i] = new BigDocument("Big Document # " + i);
}
else
{
folder[i] = new LittleDocument("Little Document # " + i);
}
}

foreach(Document doc in folder)
{
//cast the document to the various interfaces
IStorable isStorableDoc = doc as IStorable;
if(isStorableDoc != null)
{
isStorableDoc.Read();
}
else
{
Console.WriteLine("IStorable not supported");
}

ICompressible icDoc = doc as ICompressible;
if(icDoc!=null)
{
icDoc.Compress();
}
else
{
Console.WriteLine("Compressible not supported");
}

ILoggedCompressible ilcDoc = doc as ILoggedCompressible;
if (ilcDoc != null)
{
ilcDoc.LogSavedBytes();
ilcDoc.Compress();
//ilcDoc.Read();
}
else
{
Console.WriteLine("LoggedCompressible not supported");
}

IStorableCompressible isc = doc as IStorableCompressible;
if (isc!=null)
{
isc.LogOriginalSize(); //IStorableCompressible
isc.LogSavedBytes(); //ILoggedCompressible
isc.Compress(); //ICompressible
isc.Read(); //IStorable
}
else
{
Console.WriteLine("StorableCompressible not supported");
}

IEncryptable ie = doc as IEncryptable;
if (ie != null)
{
ie.Encrypt();
}
else
{
Console.WriteLine("Encryptable not supported");
}

} //end for
} //end main
} //end class
} //end namespace




using System;

namespace overridingInterface
{
interface IStorable
{
void Read();
void Write();
}

//simplify Document to implement only IStorable
public class Document : IStorable
{
//the document constructor
public Document(string s)
{
Console.WriteLine("* Public class Document: IStorable *");
Console.WriteLine("Creating document with {0}", s);
}

//make read virtual
public virtual void Read()
{
Console.WriteLine("* Public class Document: IStorable *");
Console.WriteLine("Document Read Method for IStorable");
}

//NB: Not virtual!
public void Write()
{
Console.WriteLine("* Public class Document: IStorable *");
Console.WriteLine("Document Write Method for IStorable");
}
}

//Derive from Document
public class Note : Document
{
public Note(String s) : base(s)
{
Console.WriteLine("Creating note with: {0}", s);
}

//override read method

public override void Read()
{
Console.WriteLine("Overriding the Read method for Note!");
}

//implement my own Write method
public new void Write()
{
Console.WriteLine("Implementing the Write method for note!");
}
}


//In tester, the read and write methods are called in four ways
//through the base class reference to a derived object
//through an interface created from the base class reference to the derived object
//through a derived object
//through an interface created from the derived object
public class Tester
{
static void Main()
{
//create a document reference to a Note object
Document theNote = new Note("Test Note");
IStorable isNote = theNote as IStorable;
if(isNote != null)
{
isNote.Read();
isNote.Write();
}

Console.WriteLine("\n");

//direct call to the methods
theNote.Read();
theNote.Write();

Console.WriteLine("\n");

//create a note object
Note note2 = new Note("Second Test");
IStorable isNote2 = note2 as IStorable;
if (isNote2 != null)
{
Console.WriteLine("isNote2 != null");
isNote2.Read();
isNote2.Write();
}

Console.WriteLine("\n");

//directly call the methods
note2.Read();
note2.Write();
}
}
}




using System;

namespace Programming_CSharp
{
//a simple class to store in the array
public class Employee
{
public Employee(int empID)
{
this.empID = empID;
}
public override string ToString()
{
string empIDString = "Employee ID " + empID.ToString();
return empIDString;
}
private int empID;
} //end class Employee

public class Tester
{
static void Main()
{
int[] intArray;
Employee[] empArray;
intArray = new int[5];
empArray = new Employee[3];

//populate the array
for (int i = 0; i < empArray.Length; i++)
{
empArray[i] = new Employee(i + 5);
}

for (int i = 0; i < intArray.Length; i++)
{
Console.WriteLine(intArray[i].ToString());
}

for (int i = 0; i < empArray.Length; i++)
{
Console.WriteLine(empArray[i].ToString());
}
}
}
}




using System;
using System.Collections.Generic;
using System.Text;

namespace UsingForEach
{
//a simple class to store in the array
public class Employee
{
public Employee(int empID)
{
this.empID = empID;
}
public override string ToString()
{
string empString = "Employee ID " + empID.ToString();
return empString;
}

private int empID;
}

public class Tester
{
static void Main()
{
int[] intArray;
Employee[] empArray;
intArray = new int[5];
empArray = new Employee[3];

//populate the array
for (int i = 0; i < empArray.Length; i++)
{
empArray[i] = new Employee(i + 5);
}

foreach (int i in intArray)
{
Console.WriteLine(i.ToString());
}

foreach (Employee e in empArray)
{
Console.WriteLine(e.ToString());
}
}
}
}//end namespace




using System;
using System.Collections.Generic;

//implement a simplified, singly linked, sortable list

namespace UsingConstraints
{
public class Employee : IComparable
{
private string name;
public Employee(string name)
{
this.name = name;
}
public override string ToString()
{
return this.name;
}

//implement the interface
public int CompareTo(Employee rhs)
{
return this.name.CompareTo(rhs.name);
}
public bool Equals(Employee rhs)
{
return this.name == rhs.name;
}
} // end class Employee

//node must implement IComparable of Node of T
// constrain Nodes to only take items that implement IComparable
//by using the where keyword.

public class Node<T> :
IComparable<Node<T>> where T : IComparable<T>
{
//member fields
private T data;
private Node<T> next = null;
private Node<T> prev = null;

//constructor
public Node(T data)
{
this.data = data;
}

//properties
public T Data { get { return this.data; } }

public Node<T> Next
{
get { return this.next; }
}

public int CompareTo(Node<T> rhs)
{
//this works because of the constraint
return data.CompareTo(rhs.data);
}

public bool Equals(Node<T> rhs)
{
return this.data.Equals(rhs.data);
}

//methods
public Node Add(Node<T> newNode)
{
if(this.CompareTo(newNode) > 0) // goes before me
{
newNode.next = this;//new node points to me

//if i have a previous, set it to point
//the new node as its next
if(this.prev != null)
{
this.prev.next = newNode;
newNode.prev = this.prev;
}

//set prev in current node to point to new node
this.prev = newNode;
//return the newNode in case it is the new head
return newNode;
}
else //goes after me
{
// if I have a next, pass the new node along for comparison
if (this.next != null)
{
this.next.Add(newNode);
}

// I don't have a next so set the new node to be my next
//and set its prev to point to me
else
{
this.next = newNode;
newNode.prev = this;
}

return this;
}
}

public override string ToString()
{
string output = data.ToString();

if(next != null)
{
output += ", " + next.ToString();
}

return output;
}
}//end class Node

public class LinkedList<T> where T : IComparable<T>
{
//member fields
private Node<T> headNode = null;
//properties
//indexer

public T this[int index]
{
get{
int ctr = 0;
Node<T> node = headNode;
while (node != null && ctr <= index)
{
if (ctr == index)
{
return node.Data;
}
else
{
node = node.Next;
}

++ctr;
} //end while
throw new ArgumentOutOfRangeException();
}//end get
}//end indexer

//constructor
public LinkedList()
{
}

//methods
public void Add(T data)
{
if(headNode==null)
{
headNode = new Node(data);
}
else
{
headNode = headNode.Add(new Node(data));
}
}
public override string ToString()
{
if (this.headNode != null)
{
return this.headNode.ToString();
}
else
{
return string.Empty;
}
}
}//end class

//test engine
class Test
{
//entry point
static void Main(string[] args)
{
//make an instance, run the method
Test t = new Test();
t.Run();
}

public void Run()
{
LinkedList myLinkedList = new LinkedList();
Random rand = new Random();
Console.Write("Adding: ");

for(int i = 0; i < 10; i++)
{
int nextInt = rand.Next(10);
Console.Write("{0} ", nextInt);
myLinkedList.Add(nextInt);
}

LinkedList employees = new LinkedList();
employees.Add(new Employee("Douglass"));
employees.Add(new Employee("Paul"));
employees.Add(new Employee("George"));
employees.Add(new Employee("Ringo"));

Console.WriteLine("\nRetrieving collections...");
Console.WriteLine("Integers: " + myLinkedList);
Console.WriteLine("Employees: " + employees);
}
}
}//end namespace




using System;

class MainClass
{
public static void Main()
{
int[] sample = new int[10];
int i;

for(i=0; i<10; i=i+1)
{
sample[i] = i;
}

for(i=0; i<10; i=i+1)
{
Console.WriteLine("Sample[" + i + "]: " + sample[i]);
}
}
}


Thursday, July 21, 2011


using System;

namespace abstract_method_and_class
{
abstract public class Control
{
protected int top;
protected int left;

//constructor takes two integers to fix locatio on the console
protected Control(int top, int left)
{
this.top = top;
this.left = left;
}

//simulates drawing the window
//notice: no implementation
abstract public void DrawWindow();
}

//ListBox derives from Control
public class ListBox : Control
{
private string listBoxContents; // new member variable

//constructor adds a parameter
public ListBox(int top, int left, string contents)
: base(top, left) //call base constructor
{
listBoxContents = contents;
}

//an overridden version implementing the abstract method

public override void DrawWindow()
{
Console.WriteLine("------------------------");
Console.WriteLine("Writing string to the listbox: {0}", listBoxContents);
Console.WriteLine("------------------------");
}
}

public class Button : Control
{
public Button(int top, int left)
: base(top, left)
{
}

//implement the abstract method
public override void DrawWindow()
{
Console.WriteLine("*************************");
Console.WriteLine("Drawing a button at {0}, {1}\n", top, left);
Console.WriteLine("*************************");
}
}

class Program
{
static void Main(string[] args)
{
Control[] winArray = new Control[3];
winArray[0] = new ListBox(1, 2, "First List Box");
winArray[1] = new ListBox(3, 4, "Second List Box");
winArray[2] = new Button(5, 6);

for (int i = 0; i < 3; i++)
{
winArray[i].DrawWindow();
}
}
} //end class Program
}




using System;

namespace Inheriting_From_Object
{
public class SomeClass
{
private int val;
public SomeClass(int someVal)
{
val = someVal;
}

public override string ToString()
{
return val.ToString();
}
}

class Program
{
static void DisplayValue(object o)
{
Console.WriteLine("The value of the object passed in is {0}", o);
}

static void Main(string[] AssemblyLoadEventArgs)
{

int i = 5;
Console.WriteLine("The value of i is: {0}", i.ToString());
DisplayValue(i);

SomeClass s = new SomeClass(7);
Console.WriteLine("The value of s is {0}", s.ToString());
DisplayValue(s);

int x = 11;
Console.WriteLine("The value of x is: {0}", x.ToString());
DisplayValue(x);
}
}
}




using System;

namespace Nested_Class
{
public class Fraction
{
private int numerator;
private int denominator;

public Fraction(int numerator, int denominator)
{
this.numerator = numerator;
this.denominator = denominator;
}

public override string ToString()
{
return String.Format("{0}/{1}", numerator, denominator);
}

internal class FractionArtist
{
public void Draw(Fraction f)
{
Console.WriteLine("Drawing the numerator: {0}", f.numerator);
Console.WriteLine("Drawing the denominator: {0}", f.denominator);
}
}
}

class program
{
static void Main(string[] args)
{
Fraction f1 = new Fraction(3, 4);
Console.WriteLine("f1: {0}", f1.ToString());

Fraction.FractionArtist fa = new Fraction.FractionArtist();
fa.Draw(f1);
}
}
}




using System;

namespace Conversions
{
public class Fraction
{
private int numerator;
private int denominator;

public Fraction(int numerator, int denominator)
{
Console.WriteLine("In Fraction Constructor(int, int)");
this.numerator = numerator;
this.denominator = denominator;
}

public Fraction(int wholeNumber)
{
Console.WriteLine("In Fraction Constructor(int)");
numerator = wholeNumber;
denominator = 1;
}

public static implicit operator Fraction(int theInt)
{
Console.WriteLine("In implicit conversion to Fraction");
return new Fraction(theInt);
}

public static explicit operator int(Fraction theFraction)
{
Console.WriteLine("In explicit conversion to int");
return theFraction.numerator / theFraction.denominator;
}

public static bool operator ==(Fraction lhs, Fraction rhs)
{
Console.WriteLine("In operator==");
if (lhs.denominator == rhs.denominator && lhs.numerator == rhs.numerator)
{
return true;
}
//code here to handle unlike fractions
return false;
}

public static bool operator !=(Fraction lhs, Fraction rhs)
{
Console.WriteLine("In operator !=");
return !(lhs == rhs);
}

public override bool Equals(object o)
{
Console.WriteLine("In method Equals");
if (!(o is Fraction))
{
return false;
}
return this == (Fraction)o;
}

public static Fraction operator +(Fraction lhs, Fraction rhs)
{
Console.WriteLine("In operator+");
if (lhs.denominator == rhs.denominator)
{
return new Fraction(lhs.numerator + rhs.numerator, lhs.denominator);
}

//simplistic soltion for unlike fractions
//1/2 + 3/4 == (1*4) + (3*2) / (2*4) == 10/8

int firstProduct = lhs.numerator * rhs.denominator;
int secondProduct = rhs.numerator * lhs.denominator;
return new Fraction(firstProduct + secondProduct, lhs.denominator * rhs.denominator);
}

public static Fraction operator -(Fraction lhs, Fraction rhs)
{

Console.WriteLine("In operator-");
if (lhs.denominator == rhs.denominator)
{
return new Fraction(lhs.numerator - rhs.numerator, lhs.denominator);
}

int firstProduct = lhs.numerator * rhs.denominator;
int secondProduct = rhs.numerator * lhs.denominator;
return new Fraction(firstProduct - secondProduct, lhs.denominator - rhs.denominator);
}

public override string ToString()
{
String s = numerator.ToString() + "/" + denominator.ToString();
return s;
}
}

class Program
{
static void Main(string[] args)
{
Fraction f1 = new Fraction(3, 4);
Console.WriteLine("f1: {0}", f1.ToString());

Fraction f2 = new Fraction(2, 4);
Console.WriteLine("f2: {0}", f2.ToString());

Fraction f3 = f1 + f2;
Console.WriteLine("f1 + f2 = f3: {0}", f3.ToString());

Fraction f4 = f3 + 5;
Console.WriteLine("f3+5 = f4: {0}", f4.ToString());

Fraction f5 = new Fraction(2, 4);
if (f5 == f2)
{
Console.WriteLine("f5: {0} == f2: {1}", f5.ToString(), f2.ToString());
}

Console.WriteLine("--------------------------------");
Fraction f6 = new Fraction(5);
Console.WriteLine("f6={0}", f6);

Fraction f7 = new Fraction(7, 2);
Console.WriteLine("f7={0}", f7);

Fraction f8 = f7+8;
Console.WriteLine("f8={0}", f8);

Fraction f9 = new Fraction(5, 2);
Console.WriteLine("f9={0}", f9);

Fraction f10 = f7 - f9;
Console.WriteLine("{0} - {1} = {2}", f7, f9, f10);

}
}
}




using System;
namespace CreatingAStruct
{
public struct Location
{
public int X { get; set; }
public int Y { get; set; }

public override string ToString()
{
return (string.Format("{0}, {1}", X, Y));
}
} //end struct Location

public class Tester
{
public void myFunc(Location loc)
{
loc.X = 50;
loc.Y = 100;
Console.WriteLine("in MyFunc: {0}", loc);
}

static void Main()
{
Location loc1 = new Location();
loc1.X = 200;
loc1.Y = 300;
Console.WriteLine("Loc1 location: {0}", loc1);

Tester t = new Tester();
t.myFunc(loc1);
Console.WriteLine("Loc1 location: {0}", loc1);
}
}
}

Wednesday, July 20, 2011

Wednesday, 7/20/2011


#region Using directives
using System;
using System.Collections.Generic;
using System.Text;
#endregion

namespace InOutRef
{
public class Time
{
//private member variables
private int Year;
private int Month;
private int Date;
private int Hour;
private int Minute;
private int Second;

//public accessor methods
public void DisplayCurrentTime()
{
System.Console.WriteLine("{0}/{1}/{2} {3}:{4}:{5}", Month, Date, Year, Hour, Minute, Second);
}

public int GetHour()
{
return Hour;
}

public void SetTime(int hr, out int min, ref int sec)
{
//if the passed in time is >= 30
//increment the minute and set second to 0
//otherwise leave both alone
if (sec >= 0)
{
Minute++;
Second = 0;
}
Hour = hr; //set to value passed in
//pas the minute and second back out
min = Minute;
sec = Second;
}

//constructor
public Time(System.DateTime dt)
{
Year = dt.Year;
Month = dt.Month;
Date = dt.Day;
Hour = dt.Hour;
Minute = dt.Minute;
Second = dt.Second;
}
}

public class Tester
{
static void Main()
{
System.DateTime currentTime = System.DateTime.Now;
Time t = new Time(currentTime);
t.DisplayCurrentTime();

int theHour = 3;
int theMinute;
int theSecond = 20;

t.SetTime(theHour, out theMinute, ref theSecond);
System.Console.WriteLine("the Minute is now: {0} and {1} seconds", theMinute, theSecond);

theSecond = 40;
t.SetTime(theHour, out theMinute, ref theSecond);
System.Console.WriteLine("the Minute is now: {0} and {1} seconds", theMinute, theSecond);
}
}
}




//the signature of a method is defined by its name and its parameter list.
//Two methods differ in their signatures if they have different names or different parameter lists.

//A class can have any number of methods, as long as each one's signature differs from that of all the others.

#region Using directives
using System;
using System.Collections.Generic;
using System.Text;
#endregion


namespace OverloadedConstructor
{
public class Time
{
//private member variables
private int Year;
private int Month;
private int Date;
private int Hour;
private int Minute;
private int Second;

//public accessor methods
public void DisplayCurrentTime()
{
System.Console.WriteLine("{0}/{1}/{2} {3}:{4}:{5}", Month, Date, Year, Hour, Minute, Second);
}

//constructors
public Time(System.DateTime dt)
{
Year = dt.Year;
Month = dt.Month;
Date = dt.Day;
Hour = dt.Hour;
Minute = dt.Minute;
Second = dt.Second; ;
}

public Time(int Year, int Month, int Date, int Hour, int Minute, int Second)
{
this.Year = Year;
this.Month = Month;
this.Date = Date;
this.Hour = Hour;
this.Minute = Minute;
this.Second = Second;
}
}

public class tester
{
static void Main()
{
System.DateTime currentTime = System.DateTime.Now;

Time t1 = new Time(currentTime);
t1.DisplayCurrentTime();

Time t2 = new Time(2007, 11, 18, 11, 03, 30);
t2.DisplayCurrentTime();
}
}
}




//by decoupling the class state from the method that accesses that state, the designer is free to change the internal state of the object as needed
#region Using directives
using System;
using System.Collections.Generic;
using System.Text;
#endregion

namespace UsingAProperty
{
public class Time
{
//private member variables
private int year;
private int month;
private int date;
private int hour;
private int minute;
private int second;

//public accessor methods
public void DisplayCurrentTime()
{
System.Console.WriteLine("Time\t: {0}/{1}/{2} {3}:{4}:{5}", month, date, year, hour, minute, second);
}

public Time(System.DateTime dt)
{
year = dt.Year;
month = dt.Month;
date = dt.Day;
hour = dt.Hour;
minute = dt.Minute;
second = dt.Second;
}

//create a property
//this creates two accessors: get and set
public int Hour
{
get
{
return hour;
}

set
{
hour = value;
}
}
}

public class Tester
{
static void Main()
{
System.DateTime currentTime = System.DateTime.Now;
Time t = new Time(currentTime);
t.DisplayCurrentTime();

int theHour = t.Hour;
System.Console.WriteLine("\nRetrieved the hour: {0}\n", theHour);
theHour++;
t.Hour = theHour;
System.Console.WriteLine("Updated the hour: {0}\n", theHour);
}
}
}




#region Using directives
using System;
using System.Collections.Generic;
using System.Text;
#endregion

namespace StaticPublicConstants
{
public class RightNow
{
//public member variables
public static readonly int Year;
public static readonly int Month;
public static readonly int Date;
public static readonly int Hour;
public static readonly int Minute;
public static readonly int Second;


static RightNow()
{
System.DateTime dt = System.DateTime.Now;
Year = dt.Year;
Month = dt.Month;
Date = dt.Day;
Hour = dt.Hour;
Minute = dt.Minute;
Second = dt.Second;
}
}

public class Tester
{
static void Main()
{
System.Console.WriteLine("This year:{0}", RightNow.Year.ToString());
}
}
}

Monday, July 18, 2011

Monday 7/18/2011


#region Using directives
using System;
using System.Collections.Generic;
using System.Text;
#endregion

namespace ContinueBreak
{
class ContinueBreak
{
static void Main(string[] args)
{
string signal = "0"; //initialize to neutral
while(signal!="X") // X indicates stop
{
Console.Write("Enter a signal: ");
signal = Console.ReadLine();

//do some work here, no matter what signal you receive
Console.WriteLine("Received: {0}", signal);

if(signal=="A")
{
//faulty - abort signal processing
//log the problem and abort
Console.WriteLine("Fault! Abort\n");
break;
}
if(signal=="O")
{
//normal traffic condition
//log and continue on
Console.WriteLine("All is well.\n");
continue;
}
//problem. Take action and then log the problem
//and then continue on
Console.WriteLine("{0} -- raise alarm!\n", signal);
}
}
}
}




#region Using directives
using System;
using System.Collections.Generic;
using System.Text;
#endregion

namespace DivisionModulus
{
class DivisionModulus
{
static void Main(string[] args)
{
int i1, i2;
float f1, f2;
double d1, d2;
decimal dec1, dec2;

i1 = 17;
i2 = 4;
f1 = 17f;
f2 = 4f;
d1 = 17;
d2 = 4;
dec1 = 17;
dec2 = 4;

Console.WriteLine("Integer:\t{0}\n float:\t\t{1}", i1 / i2, f1 / f2);
Console.WriteLine("Double:\t\t{0}\n decimal:\t{1}", d1 / d2, dec1 / dec2);
Console.WriteLine("\n Modulus:\t{0}", i1 % i2);
}
}
}




#region Using directives
using System;
using System.Collections.Generic;
using System.Text;
#endregion

namespace PrefixPostfix
{
class PrefixPostfix
{
static void Main(string[] args)
{
int valueOne = 10;
int valueTwo;
valueTwo = valueOne++;
Console.WriteLine("After postfix: {0}, {1}", valueOne, valueTwo);
valueOne = 20;
valueTwo = ++valueOne;
Console.WriteLine("After prefix: {0}, {1}", valueOne, valueTwo);
}
}
}




#region Using directives
using System;
using System.Collections.Generic;
using System.Text;
#endregion


namespace TimeClass
{
public class Time
{
//private variables
int Year;
int Month;
int Date;
int Hour;
int Minute;
int Second;

//public methods
public void DisplayCurrentTime()
{
Console.WriteLine("stub for DisplayCurrentTime");
}
}
public class Tester
{
static void Main()
{
Time t = new Time();
t.DisplayCurrentTime();
}
}
}




#region Using directives
using System;
using System.Collections.Generic;
using System.Text;
#endregion

namespace PassingValues
{
public class MyClass
{
public void SomeMethod(int firstParam, float secondParam)
{
Console.WriteLine("Here are the parameters received: {0}, {1}", firstParam, secondParam);
}
}

public class Tester
{
static void Main()
{
int howManyPeople = 5;
float pi = 3.14f;
MyClass mc = new MyClass();
mc.SomeMethod(howManyPeople, pi);
}
}
}

In this example, the constructor takes a DateTime object and initializes all the member variables based on values in that object.


#region Using directives
using System;
using System.Collections.Generic;
using System.Text;
#endregion

namespace DeclaringConstructor
{
public class Time
{
//private member variables
int Year;
int Month;
int Date;
int Hour;
int Minute;
int Second;
//public accessor methods
public void DisplayCurrentTime()
{
System.Console.WriteLine("{0}/{1}/{2} {3}:{4}:{5}", Month, Date, Year, Hour, Minute, Second);
}

//constructor
public Time(System.DateTime dt)
{
Year = dt.Year;
Month = dt.Month;
Date = dt.Day;
Hour = dt.Hour;
Minute = dt.Minute;
Second = dt.Second;
}
}

public class Tester
{
static void Main()
{
System.DateTime currentTime = System.DateTime.Now;
Time t = new Time(currentTime);
t.DisplayCurrentTime();
}
}
}




#region Using directives
using System;
using System.Collections.Generic;
using System.Text;
#endregion

namespace Initializer
{
public class Time
{
//private member variable
private int Year;
private int Month;
private int Date;
private int Hour;
private int Minute;
private int Second = 30; //initialzier

//public accessor methods
public void DisplayCurrentTime()
{
System.DateTime now = System.DateTime.Now;
System.Console.WriteLine("\nDebug\t:{0}/{1}/{2} {3}:{4}:{5}", now.Month, now.Day, now.Year, now.Hour, now.Minute, now.Second);

System.Console.WriteLine("Time\t: {0}/{1}/{2} {3}:{4}:{5}", Month, Date, Year, Hour, Minute, Second);
}

//constructors
public Time(System.DateTime dt)
{
Year = dt.Year;
Month = dt.Month;
Date = dt.Day;
Hour = dt.Hour;
Minute = dt.Minute;
Second = dt.Second; //explicit assignment
}


public Time(int Year, int Month, int Date, int Hour, int Minute)
{
this.Year = Year;
this.Month = Month;
this.Date = Date;
this.Hour = Hour;
this.Minute = Minute;
}
}

public class Tester
{
static void Main()
{
System.DateTime currentTime = System.DateTime.Now;
Time t = new Time(currentTime);
t.DisplayCurrentTime();

Time t2 = new Time(2007, 11, 18, 11, 45);
t2.DisplayCurrentTime();
}
}
}




#region Using directives
using System;
using System.Collections.Generic;
using System.Text;
#endregion

namespace StaticFields
{
public class Cat
{
//if you want to initialize a static member
//you must provide an explicit initializer
private static int instances = 0;

public Cat()
{
instances++;
}

public static void HowManyCats()
{
Console.WriteLine("{0} cats adopted", instances);
}
}

public class tester
{
static void Main()
{
Cat.HowManyCats();
Cat frisky = new Cat();
Cat.HowManyCats();
Cat whiskers = new Cat();
Cat.HowManyCats();
}
}
}




namespace usingStatement
{
class Tester
{
public static void Main()
{
using (Font theFont = new Font("Arial", 10.0f))
{
//use theFont
Console.WriteLine("using Arial");
} //compiler will call Dispose on theFont

Font anotherFont = new Font("Courier", 12.0f);
using (anotherFont)
{
//use another font
Console.WriteLine("using Courier");
}
}
}
}




#region Using directives
using System;
using System.Collections.Generic;
using System.Text;
#endregion

namespace ReturningValuesInParams
{
public class Time
{
//private member variables
private int Year;
private int Month;
private int Date;
private int Hour;
private int Minute;
private int Second;

//public accessor methods
public void DisplayCurrentTime()
{
System.Console.WriteLine("{0}/{1}/{2} {3}:{4}:{5}", Month, Date, Year, Hour, Minute, Second);
}

public int GetHour()
{
return Hour;
}

public void GetTime(ref int h, ref int m, ref int s)
{
h = Hour;
m = Minute;
s = Second;
}

//constructor
public Time(System.DateTime dt)
{
Year = dt.Year;
Month = dt.Month;
Date = dt.Day;
Hour = dt.Hour;
Minute = dt.Minute;
Second = dt.Second;
}
}

public class Tester
{
static void Main()
{
System.DateTime currentTime = System.DateTime.Now;
Time t = new Time(currentTime);
t.DisplayCurrentTime();

int theHour = 0;
int theMinute = 0;
int theSecond = 0;
t.GetTime(ref theHour, ref theMinute, ref theSecond);
System.Console.WriteLine("Current time: {0}:{1}:{2}", theHour, theMinute, theSecond);
}
}
}




using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

class program
{
static void Main(string[] args)
{
Console.WriteLine("{0} command line arguments were specified. ", args.Length);
foreach (string arg in args)
{
Console.WriteLine(arg);
}
}
}

Saturday, July 16, 2011

Saturday, 7/16/11


using System;
using System.Collections.Generic;
using System.Text;

namespace UsingGoTo
{
class UsingGoTo
{
static void Main(string[] args)
{
int i = 0;
repeat: // the label
Console.WriteLine("i: {0}", i+1);
i++;
if (i < 15)
{
goto repeat;
}
return;
}
}
}





#region using directives

using System;
using System.Collections.Generic;
using System.Text;

#endregion

namespace Whileloop
{
class WhileLoop
{
static void Main(string[] args)
{
int i = 0;
while (i < 10)
{
Console.WriteLine("i: {0}", i);
i++;
}
return;
}
}
}




#region Using directives

using System;
using System.Collections.Generic;
using System.Text;

#endregion

namespace DoWhile
{
class DoWhile
{
static int Main(string[] args)
{
int i = 11;
do
{
Console.WriteLine("i: {0}", i);
i++;
} while (i < 10);
return 0;
}
}
}
//i is initialized to 11 and the while test fails, but only after the body of the loop has run once




using System;
using System.Collections.Generic;
using System.Text;

namespace ForLoop
{
class ForLoop
{
static void Main(string[] args)
{
Console.WriteLine("In a for loop, the condition is tested before the statements are executed");
for (int i = 0; i < 100; i++)
{
Console.Write("{0} ", i);
if (i % 10 == 0)
{
Console.WriteLine("\t{0}", i);
}
}
return;
}
}
}




#region using directives

using System;
using System.Collections.Generic;
using System.Text;

#endregion

namespace ForLoopScope
{
class ForLoopScope
{
static void Main(string[] args)
{
for(int i=0; i < 100; i++)
{
Console.Write("{0}", i);
if(i % 10==0)
{
Console.WriteLine("\t{0}", i);
}
}
//Console.WriteLine("\n Final value of i: {0}", i);
//this line above fails, because the variable i is not available outside the scope of the loop itself
}
}
}

Thursday, July 14, 2011

7/14/2011


using System;
using System.Collections.Generic;
using System.Text;

namespace InitializingVariables
{
class Program
{
static void Main(string[] args)
{
int myInt = 7;
System.Console.WriteLine("Initialized, myInt: {0}", myInt);

myInt = 5;
System.Console.WriteLine("After assignment, myInt: {0}", myInt);
}
}
}


Here is tutorial 3-4


using System;

namespace SymbolicConstants
{
class SymbolicConstants
{
static void Main(string[] args)
{
const int FreezingPoint = 32; //degrees Fahrenheit
const int BoilingPoint = 212;
System.Console.WriteLine("Freezing point of water: {0}", FreezingPoint);
System.Console.WriteLine("Boiling point of water: {0}", BoilingPoint);
}
}
}


Here is tutorial 3-6


//you can create an unconditional branch in one of two ways. the first way is by invoking a method
using System;

namespace CallingAMethod
{
class CallingAMethod
{
static void Main()
{
Console.WriteLine("in Main! Calling SomeMethod()...");
SomeMethod();
Console.WriteLine("Back in Main().");
}

static void SomeMethod()
{
Console.WriteLine("Greetings from SometMethod!");
}
}
}


Lesson 3-7


using System;
class Values
{
static void Main()
{
int valueOne = 10;
int valueTwo = 20;

if (valueOne > valueTwo)
{
Console.WriteLine("ValueOne: {0} larger than ValueTwo: {1}", valueOne, valueTwo);
}
else
{
Console.WriteLine("ValueTwo: {0} larger than ValueOne: {1}", valueTwo, valueOne);
}
valueOne = 30; // set valueOne higher

if (valueOne > valueTwo)
{
valueTwo = valueOne + 1;
Console.WriteLine("\nSetting valueTwo to valueOne value, ");
Console.WriteLine("and incrementing ValueOne.\n");
Console.WriteLine("ValueOne: {0} ValueTwo: {1}", valueOne, valueTwo);
}
else
{
valueOne = valueTwo;
Console.WriteLine("Setting them equal. ");
Console.WriteLine("ValueOne: {0} ValueTwo: {1}", valueOne, valueTwo);
}
}
}


Here is another tutorial about nested ifs


using System;
using System.Collections.Generic;
using System.Text;

namespace NestedIf
{
class NestedIf
{
static void Main()
{
int temp = 32;
if (temp <= 32)
{
Console.WriteLine("Warning! Ice on road!");
if (temp == 32)
{
Console.WriteLine("Temp exactly freezing. Beware of water.");
}
else
{
Console.WriteLine("Watch for black ice! Temp: {0}", temp);
}
}//end if (temp <=32)
}//end main
} //end class
}//end namespace


Here is the final tutorial for the day:


using System;
class SwitchStatement
{
enum Party
{
Democrat,
ConservativeRepublican,
Republican,
Libertarian,
Liberal,
Progressive,
};
static void Main(string[] args)
{
Party myChoice = Party.Libertarian;
switch (myChoice)
{
case Party.Democrat:
Console.WriteLine("You voted Democratic. \n");
break;
case Party.ConservativeRepublican: // fall through
//Console.WriteLine("You voted Conservative.\n");
case Party.Republican:
Console.WriteLine("You voted Republican.\n");
break;
case Party.Liberal:
Console.WriteLine("Liberal is now Progressive");
goto case Party.Progressive;
case Party.Progressive:
Console.WriteLine("You voted Progressive.\n");
break;
case Party.Libertarian:
Console.WriteLine("Libertarians are voting Demcoratic");
goto case Party.Democrat;
default:
Console.WriteLine("You did not pick a valid choice.\n");
break;
}
Console.WriteLine("Thank you for voting.");
}
}