Sobes.tech
Middle

Mis on boxing ja unboxing C#-s ja kuidas neid protsesse vältida?

sobes.tech AI

Vastus AI-lt

Boxing is the implicit conversion of a value type to a reference type object or any other reference type derived from object. During this process, the value is placed in a new memory area on the managed heap.

Unboxing is the explicit conversion from a reference type object to a value type. First, it checks whether the object is an instance of the desired value type, then copies its data field from the heap.

Examples:

// Boxing
int valueType = 10;
object referenceType = valueType; // valueType is boxed into object

// Unboxing
int unboxedValue = (int)referenceType; // referenceType is unboxed into int

Avoid boxing and unboxing by using generics. Generic collections and methods work directly with value types, without requiring conversion to object. This improves performance and type safety.

Example with generics:

// Using List<T> instead of ArrayList
using System.Collections.Generic;

List<int> genericList = new List<int>();
genericList.Add(10); // No boxing

int value = genericList[0]; // No unboxing

Using generics prevents the costs associated with memory allocation on the heap and data copying during boxing/unboxing, and also prevents runtime type errors.