Click here to Skip to main content
15,887,676 members
Please Sign up or sign in to vote.
1.00/5 (3 votes)
See more:
Hello,

I have gone through many articals about Generics in C# but unable to understand it's Practical use, can anybody please explain me what are the real time problems without using Generic types and how we can solve those using Generics


Thank you
Posted

I think as you "get to know" Generics, and have a "feeling" for how to use them, you will find them immensely useful. I also predict that your sense of what Generics can be used to do ... and to greatly simplify the coding of ... will come in "stages."

So, let me outline a few of what I consider the main "goodnesses" that Generics add to .NET, in order of what I believe is their easiness to understand, and the likelihood that their usefulness will be immediately visible to you.

0. for all use-cases: generics eliminate the need for type-checking in your code, and casting from Object to a specific Type: that's a pain-in-the-ass removed !

1. an immediate replacement for .NET's older data-structures

a. use of List<SomeType>, and other generic data structures like Dictionaries, Queues, Stacks, etc. are more efficient, offer more internal functionality, and make the code you write inherently more strongly-typed, easier to understand, and maintain.

2. Generics enable you to more easily express, and use, complex, "compound" data-structures

a. consider this generic code data-structure declaration:
var listOfListOfInt = new List<List<List<int>>>();
It expresses simply the concept of ... working from the inside => out, a collection of Lists of integers, each member of which contains a collection of other Lists of integers, with each member of that (second-level) List of integers containing other Lists of integers. Yes, that's quite a mouthful to write :)

To bring that down-to-earth let's try: I have an auto-repair shop; each week I write a list containing all the money paid for each repair (rounded off to whole numbers, i.e., integers); each month I store each of the four weekly lists in a month list, and each year, I store the twelve monthly lists in a year-list: I think you get the idea.

Now consider what you would have to do to build such a data-structure before Generics
ArrayList al1 = new ArrayList();
ArrayList al2;
ArrayList al3;

for (int i = 0; i < 10; i++)
{
    al2 = new ArrayList();

    for (int j = 100; j > 90; j--)
    {
        al3 = new ArrayList();

        for (int k = 200; k < 210; k++)
        {
            al3.Add(k);
        }

        al2.Add(al3);
    }

    al1.Add(al2);
}
Yes, you might say I'm cheating here in this comparison, because you can use multi-dimensional arrays in .NET., or "jagged" arrays (arrays-of-arrays), and those can be strongly-typed, where ArrayLists cannot be strongly-typed, and are only one-dimensional: internally an ArrayList uses a linked-list, and there are memory costs when you reach the limit of the number of entries in an ArrayList which triggers allocation of more memory for the ArrayList. And, with Arrays, you have to declare their size (each dimension's size) at the point you are going to start using one. With Arrays you cannot remove items, or dynamically re-allocate the number of items the Array can hold !

To sum it up: List<int> offers you a strongly-typed, flexibly variable length (you can add, and delete items, without a high overhead) storage structure that also offers many additional features, like range accessors and manipulators, etc. .NET's generic data structures usually offer better performance than their older counter-parts.

3. Generics enable you to use late-binding at run-time. So, if, based on the user's actions, at one point in time a List of integers is required, and, at another point in time a List of strings is required, you can write code using generics with "placeholder" Type declaration that can be used for both cases.

If I write a simple class using Generics:
C#
public class GenericList<T> : List<T>
{
}
I can then do this:
C#
List<int> intList = new GenericList<int>();
List<string> stringList = new GenericList<string>();

for (int i = 0; i < 10; i++)
{
    intList.Add(i);
    stringList.Add(i.ToString());
}
Admittedly, a trivial example, but I hope it gives you some ideas.

4. finally, Generics go, imho, hand-in-hand with Linq, and the synergy between those two powerful facilities, when you begin to grasp it, and become able to use it, is going to open-up a whole new dimension for you in programming "elegantly," and efficiently.

You might enjoy reading Eric Lippert's (he is one of Microsoft's most articulate guru-level .NET experts) blog entry on "Arrays:" [^].
 
Share this answer
 
v2
Comments
Thomas Daniels 5-Sep-13 13:38pm    
+5!

I also edited your answer to fix some minor formatting issues.
BillWoodruff 5-Sep-13 21:32pm    
Well, PogramFox ... thanks ! I upvoted your answer, which contains an excellent list of resources on Generics, a few days ago. I still feel unsatisfied with my response here from a pedagogic point of view, but my standards for technical writing are very high, a result of being involved with it over thirty years on a professional level :) yours, Bill
I did not 'love' generics too much when first introduced as generics introduce one more level of darkness into their implementation code. But generics are of great help when coding your application logic (your code can be more readable as you'll not need type castings) and in terms of code reuse.

Take one look into these .net classes: List<>, Dictionary<>, Queue<>. If you need to maintain lists or queues of arbitrary types for usage in your application you will not need to implement one list class type for each and every one. Same happens with dictionaries.
 
Share this answer
 
please refer this article for clear understanding of Generics.
http://www.tutorialspoint.com/csharp/csharp_generics.htm

Regards,
Mubin
 
Share this answer
 
It is hard to convince one from the real usefulness of generics, since most (all?) of the things that can be coded with generics, can also be coded without them. But with them you will have an other level of reusability (which is an important OO feature in general) and smaller/cleaner code - thus faster development and easier maintenance; from other point of view: lower lifecycle costs of your application. So I suggest you start using them, and you will see, that they will make your life easier.
 
Share this answer
 
Copied from MSDN "Generics introduce to the .NET Framework the concept of type parameters, which make it possible to design classes and methods that defer the specification of one or more types until the class or method is declared and instantiated by client code"
Lets use an example assume that you want to create a new data type or a function that will serve a variety of data types like the List<t>, the List<t> don't care what is the data type that it holds. The behavior of the List<t> will not (or shouldn't) changed for each type supported by the
Generic Type for example the methods Add, Remove will operate the same on List<int>, List<float>, List<person>.
Generics is one of the powerful advantage that exist in .net framework
I'm strongly recommend you to keep reading and practice this.
 
Share this answer
 
v4

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900