Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do generics do boxing / unboxing when I keep Object type to the collection

Tags:

c#

If I have a list that holds the Object in it like this:

List<object> t = new List<object>();
t.Add(10);
t.Add("xyx");

in this case if I fetch back the list items do I need to unbox them?

like image 474
NoviceToDotNet Avatar asked Dec 10 '25 09:12

NoviceToDotNet


2 Answers

"Unboxing" only occurs if you have used an object to hold a value type.

In your example, the t.Add(10); is indeed boxing an int value type as an object, so it will have to be unboxed when you access it.

However, the t.Add("xyx"); is adding a string reference type, so it will NOT be boxed and it will NOT need to be unboxed when you access it.

In both cases, however, you must cast the value to the correct type in order to access it as that type.

like image 78
Matthew Watson Avatar answered Dec 11 '25 22:12

Matthew Watson


if you need treat them like objects of specific type, yes.

var o = t[0]; //this is object
var i = (int)t[0]; //this is int
like image 36
Tigran Avatar answered Dec 11 '25 23:12

Tigran