Custom List Implementation with CollectionBase

Hi. In this post I’ll show how to implement custom list in C#. Custom List Implementation with CollectionBase will be so easy.

CollectionBase

Before Starting

Maybe you should check this link to get some informations.

Let inherit the CollectionBase Class. In this example we will use its members.

Create New Class with CollectionBase

I created a class like this.

If you know Generics you’ll understand why I used Type. This class will have some methods. Let’s start coding.

Return the Instance as an array

If you have used lists or arrays you know what I’m saying. For example we have a list with some data. Let’s suppose should be like this.

When we try to access the elements of the list, we use this code:

We need to return class itself as an array. For example:

Set Method

We’ll use this method when we want to add data to the list.

It seems like List’s add Method. Actually already so.

Append Method

If we want to Insert new data to the list we can use this method. You must declare index of data when you use this method.

Include Method

If you are wondering if our data is in the list you should use this method.

Del Method

You should use this method when you need to delete data from the list.

Update Method

If you want to update the data in a list use this method. This method firstly will get value’s index. After that it will change old value with new value

Clear Method

This method will temporarily delete all the data in the list. We used new keyword. Because our class has a base class, and this base class also has a property. Without the new at the start of the function decleration we will get the warning flag.

GetEnumerator Method

We declared this method becausea class must have the getenumerator method to be enumerable.

All Class Codes

Sample Usage

Issues:

For example you’ll use Update method and you have some data with same names.

Our list doesn’t know which data we want to change. In this example, the first data will change. But you want to last data.

That’s all. Now you know how to implement lists in C#.