Reading the book VS 2010 by John Sharp, it says that generics allows to remove the need of casting, decrease boxing of values types – decrease? I thought its removed as well as casting?
Could anyone explain please?
Reading the book VS 2010 by John Sharp, it says that generics allows to
Share
It doesn’t completely remove the uses of boxing and casting… it just greatly decreases them. Sometimes you do know more than the compiler about the types of things. For example, suppose you’ve hooked up the same event handler to lots of buttons. It’s not at all unreasonable to use:
There we go – casting isn’t dead.
Likewise boxing still occurs, in situations where you don’t know the exact type at compile time and can’t express it generically. The two most obvious examples of this are:
object, boxing if necessary)Dynamic typing in C# 4:
So boxing isn’t dead either.
If you’re only talking about storing values in collections, then it’s true that boxing and casting now appears in code much, much less frequently than it used to. But not everything is in a collection, and generics are useful beyond collections, too.