Protecting Against Double Disposal

   
 
using System;
public class MyClass : IDisposable
{
    private string name;
    public MyClass(string name) { this.name = name; }
    override public string ToString() { return name; }
   
    ~MyClass() 
    { 
        Dispose();
        Console.WriteLine("~MyClass()"); 
    }
   
    private bool AlreadyDisposed = false;
   
    public void Dispose()
    {
        if (!AlreadyDisposed)
        {
            AlreadyDisposed = true;
            Console.WriteLine("Dispose()");
            GC.SuppressFinalize(this);
        }
    }
}


public class MainClass
{
    public static void Main(string[] args)
    {
        MyClass t = new MyClass("Foo");
        Console.WriteLine(t);
   
        t.Dispose();
        t.Dispose();
   
        GC.Collect();
        GC.WaitForPendingFinalizers();
    }
}

    


Derived Disposable Classes


using System;
public class MyClass : IDisposable
{
    protected string name;
    public MyClass(string name) { this.name = name; }
    override public string ToString() { return name; }
    ~MyClass() { Dispose(); Console.WriteLine("~MyClass()"); }
    public void Dispose()
    {
        Console.WriteLine("MyClass.Dispose()");
        GC.SuppressFinalize(this);
    }
}
public class SonOfMyClass : MyClass, IDisposable
{
    public SonOfMyClass(string name) : base(name) { }
    override public string ToString() {
       return name;
    }
    ~SonOfMyClass() {
       Dispose();
       Console.WriteLine("~SonOfMyClass()");
    }
    new public void Dispose()
    {
        base.Dispose();
        GC.SuppressFinalize(this);
    }
}

class DerivedDisposeApp
{
    static void Main(string[] args)
    {
        DoSomething();
    }
    static void DoSomething()
    {
        SonOfMyClass s = new SonOfMyClass("Bar");
        Console.WriteLine(s);
        s.Dispose();
    }
}

The IDisposable Interface

using System;
public class MyClass : IDisposable
{
private string name;
public MyClass(string name) { this.name = name; }
override public string ToString() { return name; }

~MyClass()
{
Dispose();
Console.WriteLine(“~MyClass(): ” +name);
}

public void Dispose()
{
Console.WriteLine(“Dispose(): ” +name);
GC.SuppressFinalize(this);
}
}

public class DisposableApp
{
public static void Main(string[] args)
{
Console.WriteLine(“start of Main, heap used: {0}”, GC.GetTotalMemory(true));
DoSomething();
Console.WriteLine(“end of Main, heap used: {0}”, GC.GetTotalMemory(true));
}

public static void DoSomething()
{
MyClass[] ta = new MyClass[3];

for (int i = 0; i < 3; i++) { ta[i] = new MyClass(String.Format("object #" +i)); Console.WriteLine("Allocated {0} objects, heap used: {1}", i+1, GC.GetTotalMemory(true)); } for (int i = 0; i < 3; i++) { ta[i].Dispose(); ta[i] = null; GC.Collect(); GC.WaitForPendingFinalizers(); Console.WriteLine("Disposed {0} objects, heap used: {1}",i+1, GC.GetTotalMemory(true)); } } } [/csharp]

Implements ICustomFormatter

   
 

using System;
using System.Text;

using System.Globalization;
public class WordyFormatProvider : IFormatProvider, ICustomFormatter {
    static readonly string[] _numberWords = "zero one two three four five six seven eight nine minus point".Split();

    IFormatProvider _parent;   // Allows consumers to chain format providers

    public WordyFormatProvider() : this(CultureInfo.CurrentCulture) { }
    public WordyFormatProvider(IFormatProvider parent) {
        _parent = parent;
    }

    public object GetFormat(Type formatType) {
        if (formatType == typeof(ICustomFormatter)) return this;
        return null;
    }

    public string Format(string format, object arg, IFormatProvider prov) {
        if (arg == null || format != "W")
            return string.Format(_parent, "{0:" + format + "}", arg);

        StringBuilder result = new StringBuilder();
        string digitList = string.Format(CultureInfo.InvariantCulture,
                                          "{0}", arg);
        foreach (char digit in digitList) {
            int i = "0123456789-.".IndexOf(digit);
            if (i == -1) continue;
            if (result.Length > 0) result.Append(&#039; &#039;);
            result.Append(_numberWords[i]);
        }
        return result.ToString();
    }
}


public class MainClass {
    public static void Main() {

        double n = -123.45;
        IFormatProvider fp = new WordyFormatProvider();
        Console.WriteLine(string.Format(fp, "{0:C} in words is {0:W}", n));
    }
}

    


Gets the hash code for an object using a comparer. Correctly handles null.

   
 

//******************************
// Written by Peter Golde
// Copyright (c) 2004-2007, Wintellect
//
// Use and restribution of this code is subject to the license agreement 
// contained in the file "License.txt" accompanying this file.
//******************************

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


namespace Wintellect.PowerCollections
{
  /// <summary>
  /// A holder class for various internal utility functions that need to be shared.
  /// </summary>
    internal static class Util
    {
        /// <summary>
        /// Gets the hash code for an object using a comparer. Correctly handles
        /// null.
        /// </summary>
        /// <param name="item">Item to get hash code for. Can be null.</param>
        /// <param name="equalityComparer">The comparer to use.</param>
        /// <returns>The hash code for the item.</returns>
        public static int GetHashCode<T>(T item, IEqualityComparer<T> equalityComparer)
        {
            if (item == null)
                return 0x1786E23C;
            else
                return equalityComparer.GetHashCode(item);
        }
   }
}

   
     


Implement IComparer

   
  

using System;
using System.Collections;

class Album : IComparable, ICloneable {
    private string _Title;
    private string _Artist;

    public Album(string artist, string title) {
        _Artist = artist;
        _Title = title;
    }

    public string Title {
        get {
            return _Title;
        }
        set {
            _Title = value;
        }
    }

    public string Artist {
        get {
            return _Artist;
        }
        set {
            _Artist = value;
        }
    }
    public override string ToString() {
        return _Artist + ",	" + _Title;
    }
    public int CompareTo(object o) {
        Album other = o as Album;
        if (other == null)
            throw new ArgumentException();
        if (_Artist != other._Artist)
            return _Artist.CompareTo(other._Artist);
        else
            return _Title.CompareTo(other._Title);
    }
    public object Clone() {
        return new Album(_Artist, _Title);
    }
}

class TitleComparer : IComparer {
    public int Compare(object l, object r) {
        Album left = l as Album;
        Album right = r as Album;
        if ((left == null) || (right == null))
            throw new ArgumentException();
        if (left.Title != right.Title)
            return left.Title.CompareTo(right.Title);
        else
            return left.Artist.CompareTo(right.Artist);
    }
}
class Class1 {
    static void Main(string[] args) {
        ArrayList arr = new ArrayList();

        arr.Add(new Album("G", "A"));
        arr.Add(new Album("B", "G"));
        arr.Add(new Album("S", "A"));

        arr.Sort();
   
        try {
            foreach (Album a in arr) {
                Console.WriteLine(a);
            }
        } catch (System.InvalidCastException e) {
        }

        arr.Sort(new TitleComparer());
        foreach (Album a in arr) {
            Console.WriteLine(a);
        }

        Album l = new Album("L", "G");
        arr.Sort();
        int index = arr.BinarySearch(l);
        Console.WriteLine(index.ToString());
        arr.Sort(new TitleComparer());
        index = arr.BinarySearch(l, new TitleComparer());
        Console.WriteLine(index.ToString());
    }
}

   
     


Implement ICloneable, IComparable

   
 

using System;
using System.Runtime.Serialization;
using System.Collections;


public class ComplexOverflowException : ApplicationException {
    public ComplexOverflowException() :
        base() {
    }
    public ComplexOverflowException(string msg) :
        base(msg) {
    }
    public ComplexOverflowException(SerializationInfo info, StreamingContext cxt) :
        base(info, cxt) {
    }
    public ComplexOverflowException(string msg, Exception inner) :
        base(msg, inner) {
    }
}

public class Complex : ICloneable, IComparable {
    private double realPart = 0.0;
    private double imagPart = 0.0;

    public Complex() {
    }

    public Complex(double r) : this(r, 0) {
    }

    public Complex(double r, double i) {
        realPart = r;
        imagPart = i;
    }

    public Complex(Complex l) {
        realPart = l.realPart;
        imagPart = l.imagPart;
    }

    public double Imaginary {
        get {
            return imagPart;
        }
        set {
            imagPart = value;
        }
    }

    public double Real {
        get {
            return realPart;
        }
        set {
            realPart = value;
        }
    }

    public void Scale(double val) {
        double tempImaginary = val * imagPart;
        realPart *= val;
        imagPart = tempImaginary;
    }

    static public Complex operator +(Complex l, Complex r) {
        Complex result = new Complex(l);
        result.realPart += r.realPart;
        result.imagPart += r.imagPart;
        return result;
    }

    static public Complex operator *(Complex l, Complex r) {
        Complex result = new Complex();
        checked {
            result.Real = l.Real * r.Real - l.Imaginary * r.Imaginary;
            result.Imaginary = l.Real * r.Imaginary + l.Imaginary * r.Real;
        }
        return result;
    }

    static public bool operator ==(Complex l, Complex r) {
        return ((l.Real == r.Real) &amp;&amp;
            (l.Imaginary == r.Imaginary));
    }

    static public bool operator !=(Complex l, Complex r) {
        return !(l == r);
    }

    static public bool operator >(Complex l, Complex r) {
        double normL = l.imagPart * l.imagPart + l.realPart * l.realPart;
        double normR = r.imagPart * r.imagPart + r.realPart * r.realPart;
        return normL > normR;
    }

    static public bool operator <(Complex l, Complex r) {
        return r > l;
    }

    public override bool Equals(object o) {
        if (!(o is Complex))
            return false;
        Complex c = (Complex)o;
        return ((c.Real == Real) &amp;&amp; (c.Imaginary == Imaginary));
    }
    public override int GetHashCode() {
        return (int)(Real + Imaginary);
    }
    object ICloneable.Clone() {
        return new Complex(this);
    }
    int IComparable.CompareTo(object o) {
        if (!(o is Complex))
            throw new ArgumentException("Object is not a complex number");
        Complex c = (Complex)o;
        double norm = imagPart * imagPart + realPart * realPart;
        double normO = c.imagPart * c.imagPart + c.realPart * c.realPart;
        if (norm > normO)
            return 1;
        else if (normO > norm)
            return -1;
        else
            return 0;
    }
}

class MainClass {

    public static IComparable theMax(IComparable seed, IEnumerable coll) {
        foreach (IComparable c in coll) {
            if (c.CompareTo(seed) > 0) {
                seed = c;
            }
        }
        return seed;
    }

    static void Main(string[] args) {
        Complex[] cArray = new Complex[100];

        Complex max = new Complex(0, 0);
        max = (Complex)theMax(max, cArray);
    }
}