using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Examples
{
class Program
{
static void Main()
{
Chemical water = new Chemical("water", 32, 212);
Chemical nitrogen = new Chemical("nitrogen", -500, -120);
Chemical h2o = new Chemical("h2o", 32, 212);
Console.WriteLine(LiquidChemical.sortPair(water, nitrogen));
Console.WriteLine(GaseousChemical.sortPair(water, nitrogen));
Console.WriteLine(GaseousChemical.sortPair(h2o, nitrogen));
Console.Read();
}
}
public class Chemical
{
private string name;
public string Name
{
get { return name; }
set { name = value; }
}
private int freezingPoint;
public int FreezingPoint
{
get { return freezingPoint; }
set { freezingPoint = value; }
}
private int boilingPoint;
public int BoilingPoint
{
get { return boilingPoint; }
set { boilingPoint = value; }
}
public Chemical(String name, int freezingPoint, int boilingPoint)
{
this.name = name;
this.boilingPoint = boilingPoint;
this.freezingPoint = freezingPoint;
}
public override string ToString()
{
return String.Format("\nname: {0}\nfreezing point: {1}\nboiling point: {2}", Name, FreezingPoint, BoilingPoint);
}
}
public class Pair
{
private T[] thePair = new T[2];
public Pair(T a, T b)
{
thePair[0] = a;
thePair[1] = b;
}
public override String ToString() {
return thePair[0].ToString() + ":" + thePair[1].ToString();
}
}
public class LiquidChemical
{
public static Pair sortPair(Chemical c1, Chemical c2)
{
return c1.FreezingPoint < c2.FreezingPoint ? new Pair(c1, c2) : new Pair(c2, c1);
}
}
public class GaseousChemical
{
public static Pair sortPair(Chemical c1, Chemical c2)
{
return String.Compare(c1.Name, c2.Name) < 0 ? new Pair(c1, c2) : new Pair(c2, c1);
}
}
}
Friday, March 28, 2008
C# Generics and My Kludgy Example
Trying to use a few basic features. Note the use of Generics in the Pair class. Closures are next I guess.