Understanding generics concept and need in C#

0 votes
asked Jul 2, 2013 in C#.NET by anonymous

I am learning C# and trying to understand the concept of generics. What is generics and where can I use it? What is the need to use generics? How does it improve the performance and help me to write better coding?

Share

1 Answer

+1 vote
answered Jul 2, 2013 by Aadhira (1,213 points)
selected Jul 3, 2013 by administrator
 
Best answer

Generic is a new concept that came with C#.Net framework 2.0. To understand generics and why it came, we may want to understand what was there before generics and what kind of problems we had. So, that we can understand what was the need for generic and how it resolves the existing issue?

Resolving Boxing and Unboxing:
Before generic concept came, if we want to create a collection of object, then we were using ArrayList. The ArrayList collection is nothing but an object that can hold any number of object which can be any data type.

If you look at the below example, ArrayList is able to hold different type of values, because any type you store, which is going to be inside the C# base type called “object”. It can hold any kind of data type value. But generics will accept only the type which we declare. You cannot store anything except that.

In the below example, ResolvingBoxingUnboxing method has arraylist ,that is holding different datatype. So, we need to do type casting whenever we want to read the data from that arraylist where as generic integer list only accepts integers so no need to do type cast.

class Program
{
    static void Main(string[] args)
    {
        GenericsDemo genericsDemo = new GenericsDemo();

        genericsDemo.ResolvingBoxingUnboxing();

        genericsDemo.ImprovingPerformance();

        Console.ReadLine();
    }      
}
public class GenericsDemo
{
    public ArrayList GetArrayList()
    {
        object temp = new object();
        temp = 20;
        return new ArrayList()
        {
            10,
            "20"
        };
    }

    public List<int> GetGenericListOfInteger()
    {
        return new List<int>()
        {
            10, 20
        };
    }

    public void ResolvingBoxingUnboxing()
    {

        ArrayList boxedCollection = GetArrayList();
        int value = 0;
        Console.WriteLine("From arraylist");
        foreach (var item in boxedCollection)
        {
            if (item is int)
            {
                value += (int)item;
            }
            else if (item is string)
            {
                int tempInt;
                int.TryParse(item.ToString(), out tempInt);
                value += tempInt;
            }
        }
        Console.WriteLine(value);

        Console.WriteLine("From generic list");
        var genericIntCollection = GetGenericListOfInteger();
        value = 0;
        foreach (var item in genericIntCollection)
        {
            value += item;
        }
        Console.WriteLine(value);

    }

    public void ImprovingPerformance()
    {
        Stopwatch stopWatch = new Stopwatch();
        stopWatch.Start();

        ArrayList nonGenericList = new ArrayList();
        for (int i = 0; i < 9999999; i++)
        {
            nonGenericList.Add(i);
        }

        for (int i = 0; i < nonGenericList.Count; i++)
        {
            int value = (int)nonGenericList[i];
            value += 1;
            nonGenericList[i] = value;
        }

        stopWatch.Stop();
        Console.WriteLine("ArrayList: " + stopWatch.ElapsedMilliseconds);

        stopWatch.Reset();
        stopWatch.Start();
        List<int> genericList = new List<int>();
        for (int i = 0; i < 9999999; i++)
        {
            genericList.Add(i);
        }

        for (int i = 0; i < genericList.Count; i++)
        {
            int value = genericList[i];
            value += 1;
            genericList[i] = value;
        }

        stopWatch.Start();
        Console.WriteLine("GenericList: " + stopWatch.ElapsedMilliseconds);
    }
}

Increasing Performance:
In the same example, in method ImprovingPerformance(), I have used array list and generic list. All I am doing is, running through a for loop and store 9999999 times integer value and then retrieve the same and do an increment. Then update the same item in the list. The activity does even in generic list.

After executing the above code, if you look at the time take,
ArrayList took 2023 milliseconds where as Generic list took only 276 milliseconds. Nearly 10 times faster because of the boxing and unboxing.

They are different kinds of generic list available with .net framework. But you can also create your own collection by inheriting the base class. But most of the time List will be used.
There is a strongly typed replacement for Hash table is using Dictionary object. It will accept 2 generic types. First one is Key and the Second one is Value

Dictionary<int, string> myDictionary = new Dictionary<int, string>();

In this example, int is key and string is value. But you can use dictionary to hold any object as key and any type of object as value

Dictionary<Guid, CustomerInfo> myDictionary = new Dictionary<Guid, CustomerInfo>();

If you have a custom class as CustomerInfo and if each customer has Guid, then you can use the above generic dictionary to hold Guid as a key and CustomerIfo as value.

Your answer

Preview

Your name to display (optional):
Privacy: Your email address will only be used for sending these notifications.
Anti-spam verification:
To avoid this verification in future, please log in or register.
site design / logo / content © 2013 - 2015 pinfaq.com
...