Home

boxingunboxing

Boxing and unboxing are terms used in programming to describe conversions between value types and reference types. Boxing wraps a value type in an object so it can be used where an object is required; unboxing extracts the original value back to its primitive or value type. These operations are common across languages that distinguish between value and reference types.

In .NET languages like C#, boxing occurs when a value type (for example int, bool, double) is

Unboxing requires that the object actually contains a boxed value of the expected type. If not, a

Practical guidance includes limiting boxing in performance-sensitive code, using generics and primitive arrays where possible, and

assigned
to
an
object
or
interface
type.
This
typically
involves
creating
a
heap-allocated
object
and
copying
the
value.
Repeated
boxing
can
incur
allocations
and
garbage
collection
overhead,
affecting
performance.
In
Java,
boxing
refers
to
converting
primitive
types
to
their
corresponding
wrapper
classes
(Integer,
Boolean,
Double),
with
auto-boxing
and
unboxing
invoked
by
the
compiler
in
many
expressions.
runtime
exception
occurs.
In
C#,
unboxing
a
non-matching
type
or
a
null
value
can
throw
InvalidCastException
or
NullReferenceException.
In
Java,
unboxing
a
null
wrapper
produces
NullPointerException,
and
unboxing
a
wrapper
of
an
incompatible
type
may
throw
ClassCastException.
being
aware
of
language-specific
features.
For
example,
Java
caches
small
integers
(roughly
-128
to
127),
which
can
reduce
boxing
overhead
in
certain
cases.
Explicit
casts
for
unboxing
can
improve
readability,
but
automatic
boxing
and
unboxing
should
be
used
judiciously
to
avoid
hidden
costs
and
surprises
in
runtime
behavior.