Mega Code Archive

 
Categories / C# / Collections Data Structure
 

CollectionBase Provides the abstract base class for a strongly typed collection

using System; using System.Collections; public class MyCollection : CollectionBase  {    public Int16 this[ int index ]  {       get  {          return( (Int16) List[index] );       }       set  {          List[index] = value;       }    }    public int Add( Int16 value )  {       return( List.Add( value ) );    }    public int IndexOf( Int16 value )  {       return( List.IndexOf( value ) );    }    public void Insert( int index, Int16 value )  {       List.Insert( index, value );    }    public void Remove( Int16 value )  {       List.Remove( value );    }    public bool Contains( Int16 value )  {       return( List.Contains( value ) );    }    protected override void OnInsert( int index, Object value )  {    }    protected override void OnRemove( int index, Object value )  {    }    protected override void OnSet( int index, Object oldValue, Object newValue )  {    }    protected override void OnValidate( Object value )  {       if ( value.GetType() != typeof(System.Int16) )          throw new ArgumentException( "value must be of type Int16.", "value" );    } } public class SamplesCollectionBase  {    public static void Main()  {       MyCollection myI16 = new MyCollection();       myI16.Add( (Int16) 1 );       myI16.Add( (Int16) 2 );       PrintValues1( myI16 );       PrintValues2( myI16 );       PrintIndexAndValues( myI16 );    }    public static void PrintIndexAndValues( MyCollection myCol )  {       for ( int i = 0; i < myCol.Count; i++ )          Console.WriteLine( "   [{0}]:   {1}", i, myCol[i] );    }    public static void PrintValues1( MyCollection myCol )  {       foreach ( Int16 i16 in myCol )          Console.WriteLine( "   {0}", i16 );    }    public static void PrintValues2( MyCollection myCol )  {       System.Collections.IEnumerator myEnumerator = myCol.GetEnumerator();       while ( myEnumerator.MoveNext() )          Console.WriteLine( "   {0}", myEnumerator.Current );    } }