Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generics or not Generics

Tags:

c#

.net

generics

Basically I have a custom List class that contains different fruits. Assume that each fruit has an ID number that is stored in the list.

Is it better to have:

new AppleList();
new OrangeList();
new LemonList();

or

new FruitList<Fruit.Apple>();
new FruitList<Fruit.Orange>();
new FruitList<Fruit.Lemon>();

Things to consider:

  • All IDs are of type int.
  • The type of the fruit will not affect the implementation of the List itself. It will only be used by the client of the list, like an external method, etc.

I would like to use the one that is clearer, better in design, faster, more efficient, etc. Additionally if these above 2 techniques are not the best, please suggest your ideas.

EDIT: Btw Fruit is an enum if that wasn't clear.

like image 604
Joan Venge Avatar asked Feb 27 '09 21:02

Joan Venge


People also ask

What is the difference between generic and non-generic?

Cost is the main difference between generic and brand name prescription drugs. Unlike brand companies, generic manufacturers compete directly on price, resulting in lower prices for consumers. Generics have saved Americans $2.2 trillion over the last decade.

Should you use generics?

Use generic types to maximize code reuse, type safety, and performance. The most common use of generics is to create collection classes. The . NET class library contains several generic collection classes in the System.

What is the disadvantages of using generics?

The Cons of Generic DrugsMedicines can look different: Trademark laws prohibit a generic drug from looking exactly like its brand-name version, so if you've switched to a generic drug, its shape, color or size may be different from what you're accustomed to taking.

What is generics and non generics in Java?

Code Reuse: With help of Generics, one needs to write a method/class/interface only once and use it for any type whereas, in non-generics, the code needs to be written again and again whenever needed.


2 Answers

Use a combo:

public class AppleList : FruitList<Apple> { ... }
public class OrangeList : FruitList<Orange> { ... }
public class LemonList : FruitList<Lemon> { ... }

Put the common logic in the base list class:

public class FruitList<T> : List<T>
    where T : IFruit 
{ ... }
like image 103
John Sheehan Avatar answered Oct 12 '22 23:10

John Sheehan


If you use generics, is there a purpose to create the FruitList type? Could you just use List?

There won't be much difference in performance, so I say why create three different classes when one would do the same exactly thing? Use the generic solution.

like image 28
Max Schmeling Avatar answered Oct 13 '22 00:10

Max Schmeling