Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there Boxing/Unboxing when casting a struct into a generic interface? [duplicate]

Possible Duplicate:
Structs, Interfaces and Boxing

From the MSDN: http://msdn.microsoft.com/en-us/library/yz2be5wk.aspx

Boxing is the process of converting a value type to the type object or to any interface type implemented by this value type.

But what about generic interfaces?

For example, int derives from both IComparable and IComparable<int>.

Let's say I have the following code:

void foo(IComparable value)    { /* etc. */ }
void bar(IComparable<T> value) { /* etc. */ }

void gizmo()
{
   int i = 42;

   bar(i); // is `i` boxed? I'd say YES
   foo(i); // is `i` boxed? I fear it is (but I hope for NO)
}

Does bar (or any function taking a non-generic interface) means there will be boxing?

Does foo (or any function taking a generic interface on the type) means there will be boxing?

Thanks.

like image 537
paercebal Avatar asked Apr 22 '11 16:04

paercebal


Video Answer


1 Answers

Any time a struct is cast to an interface, it is boxed. The purpose of IComparable<T> is to allow for something like:

void bar<T>(T value) where T : IComparable<T> { /* etc. */ }

When used in that fashion, the struct will be passed as a struct (via the generic type parameter) rather than as an interface, and thus will not have to be boxed. Note that depending upon the size of the struct, it may sometimes be better to pass by value and sometimes by reference, though of course if one is using an existing interface like IComparable one must pass as the interface demands.

like image 182
supercat Avatar answered Oct 19 '22 16:10

supercat