Translate

Sunday, April 10, 2011

System.Collections.CollectionBase example in C#

In this article I will show you a simple way to implement System.Collections.CollectionBase class, which would provide you most of the features that you would look for in a collection. I will do this by creating a console application as shown below.

For an overview of what is available in System.Collections Namespace check out
Collections Overview C#:  http://dotnetanalysis.blogspot.com/2011/04/c-collections.html


Create  class file called Human.cs and paste this code in there




using System;


namespace ConsolePlayground
{
    class Human
    {
        public string name
        {
            get;
            set;
        }
    }
}


Create a class file called HumanCollection.cs and paste this code in there



using System;
using System.Collections;


namespace ConsolePlayground
{
    class HumanCollection : CollectionBase
    {

        public void Add(Human addHu)
        {
            List.Add(addHu);
        }

        public void Remove(Human removeHu)
        {
            List.Remove(removeHu);
        }

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

    }
}

(If you don't understand what  this[int i] means, check out indexers)

Create a class file called Class1.cs and paste this code in there


using System;

namespace ConsolePlayground
{
    class Class1
    {

        public static void Main()
        {
            Human hu1 = new Human();
            hu1.name = "Clinton";

            Human hu2 = new Human();
            hu2.name = "Bush";

            Human hu3 = new Human();
            hu3.name = "Obama";

            HumanCollection Leaders = new HumanCollection();

            Leaders.Add(hu1);
            Leaders.Add(hu2);
            Leaders.Add(hu3);

            foreach (Human hu in Leaders)
            {
                Console.WriteLine(hu.name);
            }



        }


    }
}


Once you have done the above your app will look something like this
























Once you run the application, you will see this










If you play around with code above you will see that you can do all the other stuff that you would expect from a collection, such as Leaders[1].name,  Leaders.RemoveAt(0) , Leaders.Clear() etc.

No comments:

Post a Comment

Comments will appear once they have been approved by the moderator