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?
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With