Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do C# and VB have Generics? What benefit do they provide? Generics, FTW

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?

like image 668
ferventcoder Avatar asked Sep 19 '08 04:09

ferventcoder


4 Answers

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
like image 136
Mark Cidade Avatar answered Nov 15 '22 07:11

Mark Cidade


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.

like image 38
Francis B. Avatar answered Nov 15 '22 07:11

Francis B.


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.

like image 25
Amy B Avatar answered Nov 15 '22 07:11

Amy B


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.

like image 32
Jeff Hillman Avatar answered Nov 15 '22 07:11

Jeff Hillman