Custom collections in C# can be implemented using the Generics feature.

Create a class in C# that takes the Generic <T> as argument and implements the IEnumerable<T> interface. Note that any custom collection in C# should implement this Interface. Now generate the method stub for the IEnumerable<T> interface.

The two methods will be generated by the Visual Studio as follows:

#region IEnumerable<T> Members

public IEnumerator<T> GetEnumerator()

{

throw new NotImplementedException();

}

#endregion

#region IEnumerable Members

System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()

{

throw new NotImplementedException();

}

#endregion

Implement this method as follows:

#region IEnumerable<T> Members

public IEnumerator<T> GetEnumerator()

{

return this.lstList.GetEnumerator();

}

#endregion

#region IEnumerable Members

System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()

{

return this.lstList.GetEnumerator();

}

#endregion

NOTE: You need to implement both the IEnumerable<T> as well as IEnumerable methods in the custom collection since the Generic IEnumerable<T> interface extends the non generic IEnumerable interface.

Internally, in this class create a instance of Generic List as List<T> .

public class VehicleCollection<T>:IEnumerable<T>

Once you have created an object for List<T>, then add your own methods to this class as shown below.

List<T> lstList;

public VehicleCollection()

{

this.lstList= new List<T>();

}

public void Add(T obj)

{

this.lstList.Add(obj);

}

public void Clear()

{

this.lstList.Clear();

}

public int Count()

{

return this.lstList.Count;

}

public T ElementAt(int index)

{

return lstList[index];

}

public void Sort()

{

lstList.Sort();

}

Now, in code, create a Custom Class . e.g

public class Vehicle

{

public Vehicle()

{

}

public string Color { get; set; }

public float Price { get; set; }

public string Model { get; set; }

}

Now use your custom collection to store the objects of this class as follows:

//Create a instance of collection of your custom class

VehicleCollection<Vehicle> vehicleCollection = new VehicleCollection<Vehicle>();

//Create a instance of your custom class

Vehicle vehicle = new Vehicle();

vehicle.Color = "Red";

vehicle.Model = "XYZ2009";

vehicle.Price = 650000;

//Add the custom class object to the Custom Collection.

vehicleCollection.Add(vehicle);

Advertisements