Use an indexer to create a fail-soft array

image_pdfimage_print

/*
C#: The Complete Reference
by Herbert Schildt

Publisher: Osborne/McGraw-Hill (March 8, 2002)
ISBN: 0072134852
*/

// Use an indexer to create a fail-soft array.

using System;

class FailSoftArray {
int[] a; // reference to underlying array

public int Length; // Length is public

public bool errflag; // indicates outcome of last operation

// Construct array given its size.
public FailSoftArray(int size) {
a = new int[size];
Length = size;
}

// This is the indexer for FailSoftArray.
public int this[int index] {
// This is the get accessor.
get {
if(ok(index)) {
errflag = false;
return a[index];
} else {
errflag = true;
return 0;
}
}

// This is the set accessor
set {
if(ok(index)) {
a[index] = value;
errflag = false;
}
else errflag = true;
}
}

// Return true if index is within bounds.
private bool ok(int index) {
if(index >= 0 & index < Length) return true; return false; } } // Demonstrate the fail-soft array. public class FSDemo { public static void Main() { FailSoftArray fs = new FailSoftArray(5); int x; // show quiet failures Console.WriteLine("Fail quietly."); for(int i=0; i < (fs.Length * 2); i++) fs[i] = i*10; for(int i=0; i < (fs.Length * 2); i++) { x = fs[i]; if(x != -1) Console.Write(x + " "); } Console.WriteLine(); // now, generate failures Console.WriteLine(" Fail with error reports."); for(int i=0; i < (fs.Length * 2); i++) { fs[i] = i*10; if(fs.errflag) Console.WriteLine("fs[" + i + "] out-of-bounds"); } for(int i=0; i < (fs.Length * 2); i++) { x = fs[i]; if(!fs.errflag) Console.Write(x + " "); else Console.WriteLine("fs[" + i + "] out-of-bounds"); } } } [/csharp]

Indexer with complex logic

image_pdfimage_print

using System;

class MyValue {
private String[] Cards = new String[52];
public String this[int index] {
get {
return Cards[index];
}
set {
Cards[index] = value;
}
}

public String this[String CardName] {
get {
for (int i = 0; i < 52; i++) { if (Cards[i] == CardName) return Cards[i]; } return Cards[0]; } set { for (int i = 0; i < 52; i++) { if (Cards[i] == CardName) Cards[i] = value; } } } public MyValue() { int y = 0; int i = 0; while (i < 52) { for (int x = 0; x < 13; x++) { switch (y) { case 0: Cards[i] = (x + 1) + " A"; break; case 1: Cards[i] = (x + 1) + " B"; break; case 2: Cards[i] = (x + 1) + " C"; break; case 3: Cards[i] = (x + 1) + " D"; break; } if (y == 3) y = 0; else y++; i++; } } } } class MyValueClient { public static void Main() { MyValue PokerDeck = new MyValue(); String FourOfHearts = PokerDeck["4 of Hearts"]; Console.WriteLine(FourOfHearts); } } [/csharp]

indexed properties

image_pdfimage_print
   
 

using System;

public class Starter {
    public static void Main() {
        Names obj = new Names();
        Console.WriteLine(obj[1]);
    }
}

public class Names {
    object[,] _names ={{"V", 27},{"B", 35},{"D", 29}};

    public object this[int index] {
        get {
            return _names[index, 0] + " " + _names[index, 1];
        }
    }
}

    


Three dimensional Vector with IFormattable

image_pdfimage_print
   
 
using System;
using System.Collections;
using System.Text;



class MainEntryPoint {
    static void Main(string[] args) {
        Vector Vect1 = new Vector(1.0, 2.0, 5.0);
        foreach (double Component in Vect1) {
            foreach (double Next in Vect1)
                Console.Write("  " + Next);
            Console.WriteLine(Component);
        }
        Console.ReadLine();
    }
}
struct Vector : IFormattable {
    public double x, y, z;

    public IEnumerator GetEnumerator() {
        return new VectorEnumerator(this);
    }

    public Vector(double x, double y, double z) {
        this.x = x;
        this.y = y;
        this.z = z;
    }

    public string ToString(string format, IFormatProvider formatProvider) {
        if (format == null)
            return ToString();
        string formatUpper = format.ToUpper();
        switch (formatUpper) {
            case "N":
                return "|| " + Norm().ToString() + " ||";
            case "VE":
                return String.Format("( {0:E}, {1:E}, {2:E} )", x, y, z);
            case "IJK":
                StringBuilder sb = new StringBuilder(x.ToString(), 30);
                sb.Append(" i + ");
                sb.Append(y.ToString());
                sb.Append(" j + ");
                sb.Append(z.ToString());
                sb.Append(" k");
                return sb.ToString();
            default:
                return ToString();
        }
    }

    public Vector(Vector rhs) {
        x = rhs.x;
        y = rhs.y;
        z = rhs.z;
    }

    public override string ToString() {
        return "( " + x + " , " + y + " , " + z + " )";
    }

    public double this[uint i] {
        get {
            switch (i) {
                case 0:
                    return x;
                case 1:
                    return y;
                case 2:
                    return z;
                default:
                    throw new IndexOutOfRangeException(
                       "Attempt to retrieve Vector element" + i);
            }
        }
        set {
            switch (i) {
                case 0:
                    x = value;
                    break;
                case 1:
                    y = value;
                    break;
                case 2:
                    z = value;
                    break;
                default:
                    throw new IndexOutOfRangeException(
                       "Attempt to set Vector element" + i);
            }
        }
    }

    private const double Epsilon = 0.0000001;

    public static bool operator ==(Vector lhs, Vector rhs) {
        if (System.Math.Abs(lhs.x - rhs.x) < Epsilon &amp;&amp;
           System.Math.Abs(lhs.y - rhs.y) < Epsilon &amp;&amp;
           System.Math.Abs(lhs.z - rhs.z) < Epsilon)
            return true;
        else
            return false;
    }

    public static bool operator !=(Vector lhs, Vector rhs) {
        return !(lhs == rhs);
    }

    public static Vector operator +(Vector lhs, Vector rhs) {
        Vector Result = new Vector(lhs);
        Result.x += rhs.x;
        Result.y += rhs.y;
        Result.z += rhs.z;
        return Result;
    }

    public static Vector operator *(double lhs, Vector rhs) {
        return new Vector(lhs * rhs.x, lhs * rhs.y, lhs * rhs.z);
    }


    public static Vector operator *(Vector lhs, double rhs) {
        return rhs * lhs;
    }

    public static double operator *(Vector lhs, Vector rhs) {
        return lhs.x * rhs.x + lhs.y + rhs.y + lhs.z * rhs.z;
    }

    public double Norm() {
        return x * x + y * y + z * z;
    }

    private class VectorEnumerator : IEnumerator {
        Vector theVector;
        int location;

        public VectorEnumerator(Vector theVector) {
            this.theVector = theVector;
            location = -1;
        }

        public bool MoveNext() {
            ++location;
            return (location > 2) ? false : true;
        }

        public object Current {
            get {
                if (location < 0 || location > 2)
                    throw new InvalidOperationException(
                       "The enumerator is either before the first element or " +
                       "after the last element of the Vector");
                return theVector[(uint)location];
            }
        }

        public void Reset() {
            location = -1;
        }
    }
}

    


Collection is iterated using the IEnumerator interface

image_pdfimage_print
   
 

using System;
using System.Collections;

public class Starter {
    public static void Main() {
        SimpleCollection simple = new SimpleCollection(new object[] { 1, 2, 3, 4, 5, 6, 7 });
        IEnumerator enumerator = simple.GetEnumerator();
        while (enumerator.MoveNext()) {
            Console.WriteLine(enumerator.Current);
        }
    }
}

public class SimpleCollection : IEnumerable {
    public SimpleCollection(object[] array) {
        items = array;
    }
    public IEnumerator GetEnumerator() {
        return new Enumerator(items);
    }

    private object[] items = null;
}
public class Enumerator : IEnumerator {
    public Enumerator(object[] items) {
        elements = new object[items.Length];
        Array.Copy(items, elements, items.Length);
        cursor = -1;
    }
    public bool MoveNext() {
        ++cursor;
        if (cursor > (elements.Length - 1)) {
            return false;
        }
        return true;
    }
    public void Reset() {
        cursor = -1;
    }
    public object Current {
        get {
            if (cursor > (elements.Length - 1)) {
                throw new InvalidOperationException("Enumeration already finished");
            }
            if (cursor == -1) {
                throw new InvalidOperationException(
                    "Enumeration not started");
            }
            return elements[cursor];
        }
    }

    private int cursor;
    private object[] elements = null;
}
    


IEnumerator Example (Static Collection)

image_pdfimage_print
   
 

using System;
using System.Collections;
public class SimpleCollection : IEnumerable {

    public SimpleCollection(object[] array) {
        items = array;
    }

    public IEnumerator GetEnumerator() {
        return new Enumerator(this);
    }

    private class Enumerator : IEnumerator {

        public Enumerator(SimpleCollection obj) {
            oThis = obj;
            cursor = -1;
        }

        public bool MoveNext() {
            ++cursor;
            if (cursor > (oThis.items.Length - 1)) {
                return false;
            }
            return true;
        }


        public void Reset() {
            cursor = -1;
        }

        public object Current {
            get {
                if (cursor > (oThis.items.Length - 1)) {
                    throw new InvalidOperationException(

                        "Enumeration already finished");
                }
                if (cursor == -1) {
                    throw new InvalidOperationException(
                        "Enumeration not started");
                }
                return oThis.items[cursor];
            }
        }

        private int cursor;
        private SimpleCollection oThis;
    }


    private object[] items = null;
}

    


yield IEnumerator

image_pdfimage_print

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

public class Primes {
private long min;
private long max;

public Primes(long minimum, long maximum) {
min = minimum;
max = maximum;
}

public IEnumerator GetEnumerator() {
for (long possiblePrime = min; possiblePrime <= max; possiblePrime++) { bool isPrime = true; for (long possibleFactor = 2; possibleFactor <= (long)Math.Floor(Math.Sqrt(possiblePrime)); possibleFactor++) { long remainderAfterDivision = possiblePrime % possibleFactor; if (remainderAfterDivision == 0) { isPrime = false; break; } } if (isPrime) { yield return possiblePrime; } } } } class Program { static void Main(string[] args) { Primes primesFrom2To1000 = new Primes(2, 1000); foreach (long i in primesFrom2To1000) Console.Write("{0} ", i); } } [/csharp]