25 - Introduction to Generic Colleciton

25.1 Benefits of using Generic Collection

Generics provide the solution for common language runtime versions and C# language. The arrays allow the users to add and retrieve collection of objects. C# has introduced with a new feature as Generics. The benefit of generics is that it allows the creation of collections and had added features over array.

Consider an example of ArrayList in C#. The ArrayList works with the group of objects. It is similar to array but has many methods to work with. The limitation is that they work only on object. As they are operating on objects, anything can be assigned to the ArrayList. There is an increased performance overhead for converting value type objects to and from the object type. The generic collections do not require the conversion and fix the problem.

A generic collection is strongly typed. It means that only one type object can be added. The mismatch of the type is eliminated at the runtime. The type safety performance is better with value type objects because they do not incur the overhead of conversion to and from type object.

25.2 Create and use a generic list

In generic type, the declaration is similar to that of an array. Consider an example of creating a generic List <T> class. It helps to work with the strongly typed list of objects.

The code snippet of the generic list is as shown below:

class Program
{
    static void Main ( string[ ] args )
    {
        List<string> l1 = new List<string>();
        l1.Add(“John”);
        l1.Add(“Mischa”);
        l1.Add(“Matron”);
  
        foreach ( var l in l1 )
        {
            Console.WriteLine(“The user is”+l );
        }
        Console.Read();
    }
}

The output for the code is as shown below:

In the above code, the generic collection List<string> object is created. The collection is defined as List<T>, where T can be of any type. The list can contain any objects of any data type. Using the Add method, many objects of the string type can be added to the list. There are several methods as Remove, Contains, RemoveAt, etc.

The foreach loop contains the object of list string type. User can iterate through the loop to show different values in the output as shown.

Consider another example of generic list containing different methods.

class Program
{
    static void Main ( string[ ] args )
    {
        List<string> l1 = new Lisr<string>();
        l1.Add(“John”);
        l1.Add(“Mischa”);
        l1.Add(“Matron”);
        l1.RemoveAt(2);
        
        foreach ( var l in l1)
        {
            Console.WriteLine(“The user is”+l);
        }
        
        Console.WriteLine(“\nIndexOf (\”John\”):{0}”, l1.IndexOf(“John”));
        Console.WriteLine(“\nIndexOf(\”Mischa\”, 3 ):{0}”. l1.IndexOf(“Mischa”));
        
        List<int> number = new List<int>();
        number.Add(1);
        number.Add(3);
        number.Add(5);
        
        number.Reverse();
        foreach ( var n in number )
        {
            Console.WriteLine(“ The reverse is:{0}”, n);
        }
        Console.Read();
    }
}

The output for the code is as shown below:

In the above code, the method Add is used to add the values to the list control. The RemoveAt method is used to remove the element from the specified index position. The IndexOf method is used to return the index of the parameter specified.

The List number contains the integer values. The Reverse method is used to reverse the numbers of the list.

25.3 Implementation of Generic dictionary

The dictionary is a generic collection that works on a key and value pairs. The key and value pair can be of similar or different data types. The concept is generic and is applied over HashTable and has fast lookups. The elements are specified as key type and value type.

The code snippet to demonstrate the generic dictionary is as shown below:

class Program
{
    static void Main ( string[ ] args )
    {
        Dictionary<string, int> Course = new Dictionary <string, int>();
        {
            Course.Add(“Java”, 3);
            Course.Add(“C++”, 5);
            Course.Add(“VB”, 6 );

            foreach ( KeyValuePair<string, int> pair in Course )
            {
                Console.WriteLine(“{0}, {1}”, pair.Key, pair.Value);
            }
            Console.Read();
        }
    }
}

 

The output for the code is as shown below:

In the above code, the Dictionary object contains the key value pair elements. Using the foreach loop, the values are displayed on the device.

Like us on Facebook