Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why generics reduces boxing/unboxing operations

Tags:

c#

.net

generics

From here

// The .NET Framework 2.0 way to create a list
List<int> list1 = new List<int>();

// No boxing, no casting:
list1.Add(3);    

I understand there is no casting. But why no boxing happens?

"3" is on stack and list is in heap.

How it happens that value from stack moved to heap without boxing?

What happens under the hood?

like image 477
Vitaliy Avatar asked Sep 12 '25 05:09

Vitaliy


1 Answers

Boxing doesn't happen here because the array that backs the List is T[], not object[]. Therefore, the runtime knows your items are integers and doesn't need to box them.

like image 60
Simon Whitehead Avatar answered Sep 14 '25 20:09

Simon Whitehead