Use an interface constraint

image_pdfimage_print


   


using System;

class NotFoundException : ApplicationException { }

public interface IPhoneNumber {
  string Number {
    get;
    set;
  }

  string Name {
    get;
    set;
  }
}

class Friend : IPhoneNumber {
  string name;
  string number;

  public Friend(string n, string num) {
    name = n;
    number = num;
  }

  public string Number {
    get { return number; }
    set { number = value; }
  }

  public string Name {
    get { return name; }
    set { name = value; }
  }
}

class Supplier : IPhoneNumber {
  string name;
  string number;

  public Supplier(string n, string num) {
    name = n;
    number = num;
  }
  public string Number {
    get { return number; }
    set { number = value; }
  }

  public string Name {
    get { return name; }
    set { name = value; }
  }
}

class EmailFriend {
}

class PhoneList<T> where T : IPhoneNumber {
  T[] phList;
  int end;

  public PhoneList() {
    phList = new T[10];
    end = 0;
  }

  public bool add(T newEntry) {
    if(end == 10) return false;

    phList[end] = newEntry;
    end++;

    return true;
  }

  public T findByName(string name) {

    for(int i=0; i<end; i++) {

      if(phList&#91;i&#93;.Name == name)
        return phList&#91;i&#93;;

    }
    throw new NotFoundException();
  }
  public T findByNumber(string number) {

    for(int i=0; i<end; i++) {
      if(phList&#91;i&#93;.Number == number)
        return phList&#91;i&#93;;
    }
    throw new NotFoundException();
  }
}

class Test {
  public static void Main() {

    PhoneList<Friend> plist = new PhoneList<Friend>();
    plist.add(new Friend("A", "555-1111"));
    plist.add(new Friend("B", "555-6666"));
    plist.add(new Friend("C", "555-9999"));

    try {
      Friend frnd = plist.findByName("B");

      Console.Write(frnd.Name + ": " + frnd.Number);

    } catch(NotFoundException) {
      Console.WriteLine("Not Found");
    }

    Console.WriteLine();

    PhoneList<Supplier> plist2 = new PhoneList<Supplier>();
    plist2.add(new Supplier("D", "555-4444"));
    plist2.add(new Supplier("E", "555-3333"));
    plist2.add(new Supplier("F", "555-2222"));

    try {
      Supplier sp = plist2.findByNumber("555-2222");
      Console.WriteLine(sp.Name + ": " + sp.Number);
    } catch(NotFoundException) {
        Console.WriteLine("Not Found");
    }

    //PhoneList<EmailFriend> plist3 = new PhoneList<EmailFriend>(); 
  }
}
           
          


A base class constraint

image_pdfimage_print


   


using System;

class MyBase {
  public void hello() {
    Console.WriteLine("Hello");
  }
}

class B : MyBase { }

class C { }

class Test<T> where T : MyBase {
  T obj;

  public Test(T o) {
    obj = o;
  }

  public void sayHello() {
    obj.hello();
  }
}

class BaseClassConstraintDemo {
  public static void Main() {
    MyBase a = new MyBase();
    B b = new B();
    C c = new C();

    Test<MyBase> t1 = new Test<MyBase>(a);

    t1.sayHello();

    Test<B> t2 = new Test<B>(b);

    t2.sayHello();

    // The following is invalid because
    // C does not inherit MyBase.
    // Test<C> t3 = new Test<C>(c); // Error!
  }
}


           
          


Combination of Overriding Generic Methods

image_pdfimage_print
   
 

/*
Base Method    Derived Method        Comments

Nongeneric     Generic (open)        Permitted

Nongeneric     Generic (closed)      Permitted

Generic (open) Nongeneric            Not permitted

Generic (open) Generic (open)        Permitted; must use the same type parameters

Generic (open) Generic (closed)      Not permitted

Generic (closed) Nongeneric          Permitted

Generic (closed) Generic (closed)    Permitted

Generic (closed)  Generic (open)     Not permitted
*/

    


There are five types of constraints:

image_pdfimage_print
   
 
/*
    *Derivation constraints state the ascendancy of a type parameter.
    *Interface constraints are interfaces that are implemented by the type parameter.
    *Value type constraints restrict a type parameter to a value type.
    *Reference type constraints restrict a type parameter to a reference type.
    *Constructor constraints stipulate that the type parameter has a default or parameterless constructor.
*/

    


Represents a generic collection of key/value pairs. The enumerator returns the values in the order assigned.

image_pdfimage_print
   
 

//http://visualizer.codeplex.com/license
//Microsoft Public License (Ms-PL)

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

namespace Redwerb.BizArk.Core.Collections
{

    /// <summary>
    /// Represents a generic collection of key/value pairs. The enumerator returns the values in the order assigned.
    /// </summary>
    /// <typeparam name="TKey"></typeparam>
    /// <typeparam name="TValue"></typeparam>
    public class HashList<TKey, TValue>
        : IList<TValue>
    {

        #region Fields and Properties

        private Dictionary<TKey, int> mDictionary = new Dictionary<TKey, int>();
        private List<TValue> mList = new List<TValue>();

        /// <summary>
        /// Gets or sets the value for the given key.
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public TValue this[TKey key]
        {
            get { return GetValue(key); }
            set
            {
                if (mIsReadOnly) throw new InvalidOperationException("The list is readonly.");
                SetValue(key, value);
            }
        }

        /// <summary>
        /// Gets or sets the value at the designated index.
        /// </summary>
        /// <param name="index"></param>
        /// <returns></returns>
        public TValue this[int index]
        {
            get { return mList[index]; }
            set
            {
                if (mIsReadOnly) throw new InvalidOperationException("The list is readonly.");
                mList[index] = value;
            }
        }

        /// <summary>
        /// Gets the number of items in the list.
        /// </summary>
        public int Count
        {
            get { return mList.Count; }
        }

        private bool mIsReadOnly = false;
        /// <summary>
        /// Gets a value that determines if the list if readonly.
        /// </summary>
        public bool IsReadOnly
        {
            get { return mIsReadOnly; }
            protected set { mIsReadOnly = value; }
        }

        #endregion

        #region Methods

        /// <summary>
        /// Adds the value to the list.
        /// </summary>
        /// <param name="index"></param>
        /// <param name="key"></param>
        /// <param name="value"></param>
        public void Insert(int index, TKey key, TValue value)
        {
            if (mIsReadOnly) throw new InvalidOperationException("The list is readonly.");
            if (mDictionary.ContainsKey(key)) throw new ArgumentException("Key already exists in the collection.");

            mList.Insert(index, value);
            foreach (var item in mDictionary.ToArray())
            {
                if (item.Value >= index)
                    mDictionary[item.Key] = item.Value + 1;
            }
            mDictionary.Add(key, index);
        }

        /// <summary>
        /// Adds the value to the list.
        /// </summary>
        /// <param name="key"></param>
        /// <param name="value"></param>
        public void Add(TKey key, TValue value)
        {
            if (mIsReadOnly) throw new InvalidOperationException("The list is readonly.");
            if (mDictionary.ContainsKey(key)) throw new ArgumentException("Key already exists in the collection.");
            SetValue(key, value);
        }

        /// <summary>
        /// Removes the item from the list.
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public bool Remove(TKey key)
        {
            if (mIsReadOnly) throw new InvalidOperationException("The list is readonly.");
            if (!mDictionary.ContainsKey(key)) return false;
            var i = mDictionary[key];
            mDictionary.Remove(key);
            mList.RemoveAt(i);
            foreach (var item in mDictionary.ToArray())
            {
                if (item.Value > i)
                    mDictionary[item.Key] = item.Value - 1;
            }
            return true;
        }

        /// <summary>
        /// Removes the item from the list.
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public bool Remove(TValue value)
        {
            if (mIsReadOnly) throw new InvalidOperationException("The list is readonly.");
            var key = GetKey(value);
            return Remove(key);
        }

        /// <summary>
        /// Removes the value at the designated index.
        /// </summary>
        /// <param name="index"></param>
        public void RemoveAt(int index)
        {
            if (mIsReadOnly) throw new InvalidOperationException("The list is readonly.");
            var key = GetKeyFromIndex(index);
            Remove(key);
        }

        /// <summary>
        /// Removes all the items from the list.
        /// </summary>
        public void Clear()
        {
            if (mIsReadOnly) throw new InvalidOperationException("The list is readonly.");
            mDictionary.Clear();
            mList.Clear();
        }

        /// <summary>
        /// Gets the value from the list.
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        protected TValue GetValue(TKey key)
        {
            var i = mDictionary[key];
            return mList[i];
        }

        /// <summary>
        /// Gets the value from the list. If the key is not in the list, returns the default value.
        /// </summary>
        /// <param name="key"></param>
        /// <param name="dflt">Default value to return if the key does not exist.</param>
        /// <returns></returns>
        public TValue GetValue(TKey key, TValue dflt)
        {
            TValue value;
            if (TryGetValue(key, out value)) return value;
            return dflt;
        }

        /// <summary>
        /// Gets the value from the list. Returns true if the value exists, otherwise false.
        /// </summary>
        /// <param name="key"></param>
        /// <param name="value"></param>
        /// <returns></returns>
        public bool TryGetValue(TKey key, out TValue value)
        {
            if (!mDictionary.ContainsKey(key))
            {
                value = default(TValue);
                return false;
            }
            var i = mDictionary[key];
            value = mList[i];
            return true;
        }

        /// <summary>
        /// Sets the value in the list.
        /// </summary>
        /// <param name="key"></param>
        /// <param name="value"></param>
        /// <returns></returns>
        protected int SetValue(TKey key, TValue value)
        {
            int i;
            if (mDictionary.ContainsKey(key))
            {
                i = mDictionary[key];
                mList[i] = value;
            }
            else
            {
                mList.Add(value);
                i = mList.Count - 1;
                mDictionary.Add(key, i);
            }
            return i;
        }

        /// <summary>
        /// Determines if the key is in the list.
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public bool ContainsKey(TKey key)
        {
            return mDictionary.ContainsKey(key);
        }

        /// <summary>
        /// Determines if the item is in the list.
        /// </summary>
        /// <param name="item"></param>
        /// <returns></returns>
        public bool Contains(TValue item)
        {
            return mList.Contains(item);
        }

        /// <summary>
        /// Gets the index of the given item.
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public int IndexOf(TKey key)
        {
            if (!mDictionary.ContainsKey(key)) return -1;
            return mDictionary[key];
        }

        /// <summary>
        /// Gets the index of the given item.
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public int IndexOf(TValue value)
        {
            return mList.IndexOf(value);
        }

        /// <summary>
        /// Gets the key based on the value.
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public TKey GetKey(TValue value)
        {
            var i = mList.IndexOf(value);
            if (i < 0) throw new ArgumentException("Value not found in the collection.");
            foreach (var keyVal in mDictionary)
            {
                if (keyVal.Value == i)
                    return keyVal.Key;
            }
            // This should never happen, but just in case.
            throw new InvalidOperationException("The key was not found in the collection.");
        }

        /// <summary>
        /// Gets the key based on the index.
        /// </summary>
        /// <param name="index"></param>
        /// <returns></returns>
        public TKey GetKeyFromIndex(int index)
        {
            foreach (var item in mDictionary)
                if (item.Value == index) return item.Key;

            throw new ArgumentOutOfRangeException("The index was not found in the dictionary.");
        }

        /// <summary>
        /// Returns the collection of keys.
        /// </summary>
        public ICollection<TKey> Keys
        {
            get { return mDictionary.Keys; }
        }

        /// <summary>
        /// Gets the enumerator for the list.
        /// </summary>
        /// <returns></returns>
        public IEnumerator<TValue> GetEnumerator()
        {
            return mList.GetEnumerator();
        }

        /// <summary>
        /// Gets the enumerator for the list.
        /// </summary>
        /// <returns></returns>
        System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
        {
            return GetEnumerator();
        }

        /// <summary>
        /// Gets an array of the values.
        /// </summary>
        /// <returns></returns>
        public TValue[] ToArray()
        {
            return mList.ToArray();
        }

        /// <summary>
        /// Copies the values to an array.
        /// </summary>
        /// <param name="array"></param>
        /// <param name="arrayIndex"></param>
        void ICollection<TValue>.CopyTo(TValue[] array, int arrayIndex)
        {
            mList.CopyTo(array, arrayIndex);
        }

        #endregion

        #region Unsupported IList methods

        void IList<TValue>.Insert(int index, TValue item)
        {
            throw new NotSupportedException("Cannot insert values without the key.");
        }

        void ICollection<TValue>.Add(TValue item)
        {
            throw new NotSupportedException("Cannot add values without the key.");
        }

        #endregion

    }
}

   
     


Generic collection class

image_pdfimage_print
   
  
using System;
using System.Collections.Generic;

public class Bag<T> {
    private List<T> items = new List<T>();
    public void Add(T item) {
        items.Add(item);
    }
    public T Remove() {
        T item = default(T);
        if (items.Count != 0) {
            Random r = new Random();
            int num = r.Next(0, items.Count);

            item = items[num];
            items.RemoveAt(num);
        }
        return item;
    }
    public T[] RemoveAll() {
        T[] i = items.ToArray();
        items.Clear();
        return i;
    }
}
public class MainClass {
    public static void Main(string[] args) {
        Bag<string> bag = new Bag<string>();

        bag.Add("D");
        bag.Add("B");
        bag.Add("G");
        bag.Add("M");
        bag.Add("N");
        bag.Add("I");

        Console.WriteLine("Item 1 = {0}", bag.Remove());
        Console.WriteLine("Item 2 = {0}", bag.Remove());
        Console.WriteLine("Item 3 = {0}", bag.Remove());
        Console.WriteLine("Item 4 = {0}", bag.Remove());

        string[] s = bag.RemoveAll();
    }
}

   
     


Add object in a hierarchy into a generic Collection

image_pdfimage_print
   
  


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

public class Chicken : Animal {
    public void LayEgg() {
        Console.WriteLine("{0} Animal.", name);
    }

    public Chicken(string newName)
        : base(newName) {
    }
}

public class Cow : Animal {
    public void Milk() {
        Console.WriteLine("{0} cow.", name);
    }

    public Cow(string newName)
        : base(newName) {
    }
}

public abstract class Animal {
    protected string name;

    public string Name {
        get {
            return name;
        }
        set {
            name = value;
        }
    }

    public Animal() {
        name = "animal";
    }

    public Animal(string newName) {
        name = newName;
    }

    public void Feed() {
        Console.WriteLine("{0} is feeding.", name);
    }
}

class Program {
    static void Main(string[] args) {
        Collection<Animal> animalCollection = new Collection<Animal>();
        animalCollection.Add(new Cow("A"));
        animalCollection.Add(new Chicken("B"));
        foreach (Animal myAnimal in animalCollection) {
            myAnimal.Feed();
        }
    }
}