Writing Custom Generic List

kgovindarao523-21772
Posted by kgovindarao523-21772 under C# category on | Points: 40 | Views : 969
Hi,

Many of us know the importance of customizing the exceptions and can achieve this by creating our own Custom Exceptions Classes.
Like wise, Here i provide code to define Own Generic List class.

Usually, to take list of strings, we can use
List<string> oStringList=new List<string>();
and then we can perform some predefined operations like, Sort, reveres etc, on it.

Here, i want to use my customized list
for ex : CustomList<string> cStringlist = new CustomList<string>();
and want to perform customized operations like AddToList(), RemoveFromList(), showCustomListData()

Code:

//my custom generic class
public class CustomList<T>
{
T[] listData;
int listCount;
public int length;
public CustomList()
{
listData = new T[10];
listCount = 0;
length = listCount;
}
public void AddToList(T Data)
{
if (listCount < 10)
{
listData[listCount] = Data;
listCount = listCount + 1;
length = listCount;
}
else
{
try
{
Console.WriteLine("Invalid operation since data in CustomList is FULL");
Console.WriteLine("{0}", Environment.NewLine);
throw new CustomException("List data is Full");
}
catch (CustomException Ex)
{
Console.WriteLine("{0}", Environment.NewLine);
Console.WriteLine("{0}", Environment.NewLine);
Console.WriteLine("List Data is full.. U wil not proceed furthur{0}{1}", Environment.NewLine, Ex); ;
}
}
}
public void RemoveFromList()//removes last inserted data
{
if (listCount > 0)
{
listCount = listCount - 1;
length = listCount;
Console.WriteLine("Successfully removed From CustomList");
return;
}
else
{
Console.WriteLine("invalid operation since No data in CustomList ");
return;
}
}
public T showCustomListData(int position)
{
return (T)listData[position];
}
~CustomList()
{
this.listData = null;
listCount = 0;
GC.Collect();
}
}


How to call:

CustomList<string> cStringlist = new CustomList<string>();//you can use int,string etc...

cStringlist.AddToList("Hi");


cStringlist.AddToList("Hello");

cStringlist.AddToList("Welcome To");

cStringlist.AddToList("dotnetfunda");

cStringlist.AddToList(".com");

cStringlist.RemoveFromList();//removes '.com'
Console.WriteLine("{0}", Environment.NewLine);
for (int i = 0; i < cStringlist.length; i++)
{
Console.WriteLine("Data in Custom List strings are:{0}", cStringlist.showCustomListData(i).ToString());
}


Thank you.

Comments or Responses

Login to post response