C# Custom Collection Implementation


This sample shows a simple custom collection implementation in C# with the .NET Framework.

using System;
using System.Collections;

namespace Personal.Demos.Simple{

public class MainApp{

//entry point 'Main'

public static void Main(){

//get us some Widgets
Widgets MyWidgets = Initialize();

Console.WriteLine("Using 'foreach' – ");

//enumerate through the collection with
//the foreach constuct.

foreach(Widget W in MyWidgets){
//call the same method on each item in
//the collection.
Console.WriteLine(W.AMethod());
}

Console.WriteLine("Using 'Indexers' – ");

//enumerate through the collection with
//it's indexer.

for(int i=0; i < MyWidgets.Count ; i++){
//call the same method on each item in
//the collection.
Console.WriteLine(MyWidgets[i].AMethod());
}

}

//fill up a 'Widgets' collection with…
//…well some Widgets.

private static Widgets Initialize(){

Widgets colWidgets = new Widgets();
Widget objWidget;
int i;

for(i=0 ; i < 10 ; i++){
objWidget = new Widget();
objWidget.Number=i;
colWidgets.Add(objWidget);
}

return colWidgets;
}

}

//*****************************************************
//the individual Widget class

public class Widget{

public int Number=0;

public virtual string AMethod(){

return "This Widget's Number is : "
+ Number.ToString();

}
}

//*****************************************************
//Widgets collection class MUST derive from
//System.Collections.CollectionBase

public class Widgets:CollectionBase{

public virtual void Add(Widget NewWidget){
//forward our Add method on to
//CollectionBase.IList.Add
this.List.Add(NewWidget);

}

//this is the indexer (readonly)
public virtual Widget this[int Index]{

get{
//return the Widget at IList[Index]
return (Widget)this.List[Index];

}

}
}
//*****************************************************
}

Related Articles :

Twitter Digg Delicious Stumbleupon Technorati Facebook Email

No comments yet... Be the first to leave a reply!