4

Possible Duplicate:
Do generic interfaces in C# prevent boxing? (.NET vs Mono performance)

I have one quick question... by using generics, do I completely get rid of boxing/unboxing operations?

For example, by using a List do I still get lots of boxing/unboxing?

I've read several docs on the internet but couldn't solve this specific question...

Community
  • 1
  • 1
Paulo
  • 41
  • 2

2 Answers2

8

If a class was written correctly, then using generics will avoid all boxing and unboxing. Instead, the just-in-time compiler will generate code for each version of the class that correctly handles the value types appropriately.

Jeffrey L Whitledge
  • 58,241
  • 9
  • 71
  • 99
  • 1
    +1 for explicitly mentioning value types. – overslacked Mar 10 '10 at 23:55
  • -1 a class was/is never boxed or unboxed - boxing is for value types only. The advantage of generics for class objects is strong typing, not no-boxing. – pm100 Mar 11 '10 at 01:22
  • 2
    @pm100 : by "each version of the class" I mean the generic class. It has a different version for each type supplied as a parameter. The JIT creates different code for each value type supplied. It also creates a single version that handles all of the reference types. – Jeffrey L Whitledge Mar 11 '10 at 01:39
7

If you use it correctly then: Yes, it will eliminate boxing.

For instance,

List<int> table = new List<int>();
table.Add(1);
int x = table[0];

does not involve any boxing/unboxing.

H H
  • 263,252
  • 30
  • 330
  • 514