views:

989

answers:

15

From Wikipedia:

Generic programming is a style of computer programming in which algorithms are written in terms of to-be-specified-later types that are then instantiated when needed for specific types provided as parameters and was pioneered by Ada which appeared in 1983. This approach permits writing common functions or types that differ only in the set of types on which they operate when used, thus reducing duplication.

Generics provide the ability to define types that are specified later. You don't have to cast items to a type to use them because they are already typed.

Why does C# and VB have Generics? What benefit do they provide? What benefits do you find using them?

What other languages also have generics?

A: 

The common example is collections. e.g. a set of type T, as an Add(T) method and a T get() method. Same code, different type safe collections.

C++, D, Ada and others have templates, a superset of generics that do it a little different bug get the same end result (and then some).

IIRC Java has generics, but I don't do Java.

BCS
A: 

The easiest way to explain it is to give an example. Say you want two hashtables, one that maps objects of type string to type int and one that maps objects of type string to type double. You could define Hashtable and then use the K and V types. Without generics, you'd have to use the 'object' type which, in addition to having to be cast to be meaningful, gives up typesafety. Just instantiate Hashtable and Hashtable and you've got your hash tables with proper typechecking and all.

Cody Brocious
+3  A: 

C# and VB have generics to take advantage of generics support in the underlying CLR (or is the other way around?). They allow you to write code ina statically-typed language that can apply to more than one kind of type without rewriting the code for each type you use them for (the runtime will do that for you) or otherwise using System.Object and casting everywhere (like we had to do with ArrayList).

Did you read the article?

These languages also have generics:

  • C++ (via templates)
  • Ada (via templates)
  • Eiffel
  • D (via templates)
  • Haskell
  • Java
Mark Cidade
There is some difference between generics and templates. C++,Ada and D have the latter, not sure about the rest.
BCS
Templates still allow for writing with generics, in addition to other stuff.
Mark Cidade
A: 

Java also has generics. C++ has templates.

Dynamic languages like Perl and Javascript don't have the same type restrictions so they get mostly the same benefits with less work.

Wedge
Not the benefit, because they do not offer any type safety at all.
Thomas
There is much more benefit to generic collections than type safety.
Wedge
+2  A: 

From MSDN:

Generics provide the solution to a limitation in earlier versions of the common language runtime and the C# language in which generalization is accomplished by casting types to and from the universal base type Object. By creating a generic class, you can create a collection that is type-safe at compile-time.

Read the rest of that article to see some examples of how Generics can improve the readability and performance of your code.

Jeff Hillman
+5  A: 

Personally, I think they allows to save a lot of time. I'm still using .NET Framework 1.1 and every time you want a specific collection, you need to create a strongly typed collection by implementing CollectionBase. With Generics, you just need to declare your collection like that List<MyObject> and it's done.

Francis B.
+2  A: 

Probably the most common use for them is having strongly typed ArrayLists. In .NET 1.1, you'd either have to cast everything from object to your desired Type, or use something like CodeSmith to generate a strongly typed ArrayList.

Additionally, they help decrease boxing. Again, in .NET 1.x, if you tried to use an ArrayList with a Value Type, you'd end up boxing and unboxing the objects all over the place. Generics avoid that by letting you define the Type, whether Reference or Value.

There are other handy uses for them too, event handlers, LINQ queries, etc.

swilliams
+1  A: 

Generics in .NET are excellent for object collections. You can define your object type however you want and be able to have, say, a List without writing any code for that, and have access to all the efficient functionality of the .NET List generic collection while being type-safe to T. It's great stuff.

Grank
A: 

In objective-C you can use protocols to achieve the aims of generics. Since the language is weakly typed however, it's generally not as much of a concern as when you are fighting the type system to use one code path for many types.

Kendall Helmstetter Gelner
+1  A: 

Generics are build on the concept of templates in c++ if you are familiar with them.

Its a way to implement an algorithm or data structure but delaying the actual type it is used on.

List can then be assigned with any type of your choice int, string and even custom types the type is assigned on construction of the list. But you will be able to use the list operations add remove etc.

You can really save a lot of coding effort by getting used to generics. And you don't have to box and unbox between types.

Java have generics as well. They are called wildcards.

bovium
A: 

Personally I am a huge fan of generics because of all of the code I don't have to write.

http://stackoverflow.com/questions/3058/what-is-inversion-of-control#99760

ferventcoder
+1  A: 

Generics in .net, like inheritence and extension methods, allows for reduction of code duplication. Let me explain by way of refactoring.

If all classes with a common ancestor have a common method, place the common method in the classes' common ancestor (inheritence).

If some classes have a common method that uses a public contract to achieve some result, make the common method into an extension method on that public contract.

If some several methods or classes have the same code that differs only by the types acted upon (especially where the details of the type are not relevant to the operation of the method), collect those methods or classes into a generic.

David B
+1  A: 

They increase performance for collections using value types, since no boxing/unboxing will be required. They're a lot cleaner to use since you won't have to cast an object (for example using ArrayList) to the desired type - and likewise they help enforce type safety.

Scott
+1  A: 

Consider these method signatures:

//Old and busted
public abstract class Enum
{
  public static object Parse(Type enumType, string value);
}
//To call it:
MyEnum x = (MyEnum) Enum.Parse(typeof(MyEnum), someString);


//New and groovy
public abstract class Enum
{
  public static T Parse<T>(string value);
}

//To call it:
MyEnum x = Enum.Parse<MyEnum>(someString);

Look ma: No runtime type manipulation.

David B
I love your comment on look ma. :D
ferventcoder
+1  A: 

Biggest advantage of generics over non generic types in C# (not Java, Java is a different story) is that they are much faster. The JIT generates the best machine code it can come up with for a given type. List<int> is actually a list of ints and not integer objects wrapping an int. This makes generic types awesomely fast and also type safe which can help you detect an awesome lot of errors at compile time :)

Armin Ronacher