Many times, I use List. But List has a disadvantage that we cant get item like we get in arrays like: arr[i];
For this to overcome we have a class ArrayList. ArrayList supports all functionalities of list. Other than this it give the feature of retrieving the items in format: arr[i];
But in both I faced a problem that I was unable to get the Item in my type. I had to typecast it firstly then I can work on it. So to make me work directly on the List items; I have to inherit a CollectionBase. This ensures features of the List. Here I am giving the sample how to create the collection of our own type.
using System; using System.Collections;
public class Vectors : CollectionBase //CollectionBase is used to add List Functions //like Add,insert,exist etc. { int x,y; //x & y co-ordinates.
public Vectors() //Making new vector to point to origin { x=0; y=0; }
public int XCoord //Setting & Retrieving X-Co-ordinate { get { return ( x ); } set { x=value; } } public int YCoord //Setting & Retrieving X-Co-ordinate { get { return ( y ); } set { y=value; } }
public Vectors this[ int index ] //This feature make it work as an arraylist { get { return( (Vectors) List[index] ); } set { List[index] = value; } } public int Add( Vectors value ) //Add Vector to the list { return( List.Add( value ) ); }
public int IndexOf( Vectors value ) //Return Index { return( List.IndexOf( value ) ); }
public void Insert( int index, Vectors value ) { List.Insert( index, value ); }
public void Remove( Vectors value ) { List.Remove( value ); }
public bool Contains( Vectors value ) { // If value is not of type Int16, this will return false. return( List.Contains( value ) ); }
protected override void OnInsert( int index, Object value ) { // Insert additional code to be run only when inserting values. }
protected override void OnRemove( int index, Object value ) { // Insert additional code to be run only when removing values. }
protected override void OnSet( int index, Object oldValue, Object newValue ) { // Insert additional code to be run only when setting values. }
protected override void OnValidate( Object value ) { if ( value.GetType() != Type.GetType("System.Int16") ) throw new ArgumentException( "value must be of type Int16.", "value" ); }
}
The collection made here can be used easily.
|
No responses found. Be the first to respond and make money from revenue sharing program.
|