Boxing / casting are part of the downside of an early-bound,
strongly-typed environment. If all types must be known at compile time,
then you end up using object or some other common ancestor to hold
instances whose type is not known at compile time, and then you either
have to live with the reduced functionality of the ancestor or cast it
to something more useful based on some runtime decision process.
By contrast in a late bound, loosely-typed environment the runtime may
not care what an object *is* so much as what it *does*. For example if
I make a call like someObject.Fubar(), a late bound runtime may just try
to make the Fubar() call, throwing an exception only if that method
doesn't exist in someObject.
The trade off is that early binding / strong typing gives us the
benefits of type safety and (on balance anyway) better performance
because all addresses can be resolved statically at compile time rather
than dynamically at runtime.
The 2.0 version of the CLR (VS 2005) provides a mechanism called
generics that gets around some of this fuss. For example rather than
creating an ArrayList of objects to hold some variable number of ints
you can create a List<int> and the runtime will build a strongly typed
list of ints under the hood based on the template of the generic List
class. You can then get ints in and out of the collection with no
casting / boxing / unboxing, and yet the generic List<> class is
reusable for any kind of object your might desire and will work with
them all, without the need for boxing.
--Bob
Peter Olcott wrote:
Exactly why does C# and .NET require all the extra
copying of data?