Boxing and unboxing are conversions between value types and reference types. Boxing Converting a value type (int, double, struct, enum) to object or to an interface it implements. The runtime allocates an object on the heap and copies the value into it. int count = 42; object boxed = count; // boxing: heap allocation + copy Unboxing Extracting the value type from the boxed object. It requires an explicit cast to the exact original type and copies the value back. int again = (int)boxed; // unboxing long wrong = (long)boxed; // InvalidCastException: boxed int is not a long long ok = (long)(int)boxed; // unbox to int first, then convert Why it matters - Performance: each boxing allocates memory on the heap, increasing GC pressure. In hot loops this adds up. - Copy semantics: the box holds a copy. Changing the original does not affect the boxed value, and modifying a boxed struct through an interface changes only the box. Where boxing happens without you noticing - Non-generic collections: ArrayList.Add(5), Hashtable. - Calling object-typed APIs: string.Format("{0}", 5) in older APIs, Console.WriteLine(object). - Interfaces on structs: IComparable c = 5. - Calling methods inherited from object on structs that do not override them (for example GetHashCode on a struct without an override, in some cases). - Enum.HasFlag in old runtimes (optimised in modern .NET). - String concatenation with value types in old code: "Total: " + 5 (modern compilers and interpolated string handlers avoid this in many cases). How to avoid it - Use generic collections (List<int>, Dictionary<string, int>) instead of ArrayList and Hashtable. - Use generic methods with constraints instead of object parameters: void Print<T>(T value). - Implement IEquatable<T> on structs and override Equals and GetHashCode. - Use string interpolation, which in modern C# uses handlers that avoid boxing for many types. Detecting it: profilers and allocation tracking (dotnet-trace, Visual Studio diagnostics, BenchmarkDotNet's MemoryDiagnoser), or looking for box instructions in IL.
Ravindra Wadile · · 0 likes