Thursday, March 13, 2014

C# - Creating a Collection class


Creating a simple Collection class is very easy.
Assuming we have a class like this and want to create a collection class from it...

public class MyClass
{
     public string Name;

     public MyClass()
     {
     }
}

We can easily create a collection of it by using the CollectionBase class in the .NET Framework.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace My_Project.Classes
{
    public class MyClassCollection : System.Collections.CollectionBase
    {
        #region Variables
        #endregion

        #region Properties
        #endregion

        #region Constructors
        #endregion

        #region Methods

        public void Add(My_Project.Classes.MyClass NewMyClassObject)
        {
            List.Add(NewMyClassObject);
        }

        public void Remove(int index)
        {
            // Check to see if there is a MyClass at the supplied index.
            if (index > Count - 1 || index < 0)
            // If no MyClass exists, a messagebox is shown and the operation 
            // is cancelled.
            {
                throw new Exception();
            }
            else
            {
                List.RemoveAt(index);
            }
        }

        public My_Project.Classes.MyClass Item(int Index)
        {
            // The appropriate item is retrieved from the List object and
            // explicitly cast to the MyClass type, then returned to the 
            // caller.
            return (My_Project.Classes.MyClass)List[Index];
        }
        #endregion
    }
}

Now we can use the Collection class:

// create MyClass Object 1:
MyClass MyClassObject1 = new MyClass();

//create MyClass Object 2:
MyClass MyClassObject2 = new MyClass();

//creating the collection object:
MyClassCollection Col = new MyClassCollection();

//adding both objects to the collection
Col.Add(MyClassObject1);
Col.Add(MyClassObject2);

//removing an object from the collection:
Col.Remove(1);

//getting the item object from a collection
MyClass NewObject = Col.Item(0);


Here is a good walkthrough from Microsoft:

http://msdn.microsoft.com/en-us/library/xth2y6ft(v=vs.71).aspx

No comments:

Post a Comment