How do generics eliminate or decrease the need for boxing?
Reading th开发者_开发技巧e 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?
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:
public void HandleClickEvent(object sender, EventArgs e)
{
// We know it will always be a button, and we want an exception if it's not
Button button = (Button) sender;
...
}
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:
- Reflection (fetching the value of a property with reflection will give you an
object
, boxing if necessary) Dynamic typing in C# 4:
dynamic d = CreateDynamicObject(); int x = d.Foo(); // The dynamic call would have to box if necessary, // the conversion will unbox
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.
What helped me, years ago, to get to grips with generics is to consider using a generic when:
You add a parameter to a method that contains type information
public object Parse(string input, Type outputType)
// replace by:
public T Parse<T>(string input)
You use an instance field that contains type information:
class Foo
{
private Type _wrappedObjectType;
private object _wrappedObject;
}
// replace by
class Foo<T>
{
private T _wrappedObject;
}
精彩评论