Custom Collections in C# - ProgramIdea

Custom Collections in C#


.Net framework 4.5 provided a facility that helpful you to create your own custom strongly typed collections. Strongly typed collections are useful because they do not incur the performance hit due to boxing and unboxing.

To create your own custom collection, you can inherit from the CollectionBase class.

First you create a class for your collections.

class Student
{
    public string Name { get; set ; }
    public string Branch { get; set ; }
    public string City { get; set ; }
}

For making your own custom collection, you need to inherit your class to CollectionBase class that provided by .Net framework 4.5.

There are not Add, Insert, Sort, or Search method in the base class. When you implement your class, you need to implement whichever method you want to add, insert, sort or search items within the collection.

Here i create a class StudentCollection that inherit from the CollectionBase class. I implemented some method which are useful for me like Add, Insert and Remove method and also a indexer that is useful to reference an item by index.

class StudentCollection : CollectionBase
{
    public void Add(Student student)
    {
        List.Add(student);
    } 

    public void Insert(int index,Student student)
    {
        List.Insert(index, student);
    }

    public void Remove(Student student)
    {
        List.Remove(student);
    } 

    public Student this[int index]
    {
        get
        {
            return (Student)List[index];
        }
        set
        {
            List[index] = value;
        }
    }
}

Now we created our cutom collection class and need to implement that class. Below codes showing that how to use costom collection class.

 // Declare object of custom collection
StudentCollection students = new StudentCollection(); 

// Add items in custom collections
students.Add(new  Student() { Name = "Amit", Branch = "EEE" , City =  "Dihri" });
students.Add(new  Student() { Name = "Anand", Branch = "IT" , City =  "Aurangabad" });
students.Add(new  Student() { Name = "Mishra", Branch = "ECE" , City =  "Buxar" });
students.Add(new  Student() { Name = "Deepak", Branch = "ECE" , City =  "Ranchi" });
students.Add(new  Student() { Name = "Ashutosh", Branch = "CS" , City =  "Hajipur" });

// Retrieving all items from custom collections
foreach(Student student in students)
{
    Response.Write(student.Name + " - " + student.Branch + " - " + student.City);
    Response.Write("<br/>");
}

//Output 
// Amit - EEE  - Dihri
// Anand - IT - Aurangabad
// Mishra - ECE - Buxar
// Deepak - ECE - Ranchi
// Ashutosh - CS - Hajipur 

// Insert an item at specific index
students.Insert(4, new Student() { Name = "Jitesh", Branch = "ECE" , City =  "Dumraon" });

// Retrieve specific index item
Student  objStudent = students[0];