I'm studying for the .NET Framework Application Development Foundation cert and I just finished the section on generics.
I understand the concept of a generic but I cannot think of any real world use for one. I was wondering if someone wouldn't mind sharing a generic class that they actually use so I could see a real world example?
Well, you can find some examples in the .NET library itself.
Look at the collections classes. This is a good example of a case in which you don't really care about the type of an object, you just want a container for n number of them. The container doesn't have any clue if they are ints, strings, MyClass', whatever, it doesn't matter. What matters is that they can be stored and iterated through.
One of the main advantages of generic types is that they have the potential to cut back on boxing and unboxing.
For example, before generic types were introduced, if you wanted to store an instance of a class into a collection, you would have to convert that instance to an Object and insert it into an Object array. Then you would have to cast the Object back to the type you had it originally.
However, with generic types, and subsiquently generic collections, you can use something like this:
List<MyClass> list = new List<MyClass>();
list.Add(instanceOfMyClass);
This allows you to store your instances of the class as is, without having to box it as an Object and unbox it again when you want to change it back.
It also insures that only instances of MyClass can be added to the collection, not just any old Object that has originated from a Long, Int16, Bool... etc. So type security is another reason for generics.
Hope this helps!
Last edited by bassguru; January 6th, 2011 at 10:24 AM.
Reason: Syntax error
That makes much more sense. I'm also currently working on an application that uses a few different dictionaries and that also helped me to see the value of generics.
Just thought I would add that boxing is only a performance concern in the case of value types. In the case of a reference type (i.e., a class) you get strong typing as bassguru noted.
Bookmarks