Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why not always use Generics?

Tags:

.net

generics

I am reading existing posts on Generics at SO. If Generics has so many advantages like Type safety, no overhead of boxing/unboxing and it is fast, why not always use it? Why would you ever use a non-generic object instead?

Edited (Question further extended below)

I am a bit confused. The last time I read about Generics, a few months ago, I read that if the Type in the parameters is variable, Generic should be used in order to prevent errors. What I seem to be reading now, though, is that Generics limit implementation to a fixed Type, while a non-generic object allows you to define parameter types at run-time.

Please help me see what I'm missing?

Secondly, using these kinds of constructs in proper OOP designs (Generics, etc.) are helpful when you are working in a team and your code is shareable. For a lone programmer with a small scale, who knows what Type has to come in the parameter, it seems like there is no need to worry, and little difference between using a Generic or Non-Generic type. Is this accurate?

like image 922
RKh Avatar asked Oct 28 '10 07:10

RKh


People also ask

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.

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 point of using generics?

Generics enable the use of stronger type-checking, the elimination of casts, and the ability to develop generic algorithms. Without generics, many of the features that we use in Java today would not be possible.


1 Answers

In general you should - however, there are times (especially when writing library code) when it is not possible (or certainly not convenient) to know about the calling type (even in terms of T), so non-generic types (mainly interfaces such as IList, IEnumerable) are very useful. Data-binding is a good example of this. Indeed, anything that involves reflection is generally made much harder by using generics, and since (via the nature of reflection) you've already lost those benefits, you may as well just drop to non-generic code. Reflection and generics are not very good friends at all.

like image 60
Marc Gravell Avatar answered Oct 03 '22 04:10

Marc Gravell