Attention: We are retiring the ASP.NET Community Blogs. Learn more >

Boxing and collections

Standard, out of the box .NET collections store references of type System.Object.  We have a structure that we add to a collection.  We add approx 2500 structure types to this collection.

Well, duh, if we are adding a structure, which is a value type, to a collection, which stores a reference type, the structure will get boxed and allocated on the heap 2500+ times!  Its like creating a reference type 2500+ times!

Solution:  use a reference type (class) vs. a structure in this case. 

  

1 Comment

  • Boxing and unboxing is a essential concept in C#’s type system. With Boxing and unboxing one can link between value-types and reference-types by allowing any value of a value-type to be converted to and

    from type object. Boxing and unboxing enables a unified view of the type system wherein a value of any

    type can ultimately be treated as an object. Converting a value type to reference type is called Boxing. Unboxing is an explicit operation.

Comments have been disabled for this content.