Translate

Sunday, April 10, 2011

System.Collections.DictionaryBase example in C#




In this article I will show you a simple way to implement System.Collections.DictionaryBase class. 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 : DictionaryBase
    {

        public void Add(string ID, Human addHu)
        {
            Dictionary.Add(ID, addHu);
        }

        public void Remove(string ID)
        {
            Dictionary.Remove(ID);
        }

        public Human this[string ID]
        {
            get
            {
                return (Human)Dictionary[ID];
            }
            set
            {
                Dictionary[ID] = value;
            }
        }

    }
}

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


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


using System;
using System.Collections;

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("1", hu1);//Item is added as a key,value pair
            Leaders.Add("2", hu2);
            Leaders.Add("3", hu3);

            Console.WriteLine(Leaders["1"].name);//Item is accessed by key and not index
            Console.WriteLine("*************************");

            foreach (DictionaryEntry de in Leaders)
            {
                Console.WriteLine(de.Key);
                Console.WriteLine(((Human)de.Value).name);
                Console.WriteLine("*************************");
            }


        }

    }
}


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


Once you run the application, this is how the output would look like.


No comments:

Post a Comment

Comments will appear once they have been approved by the moderator

Post a Comment