Search code examples
c#boxingunboxing

C# Concept Unboxing


I'm trying to learn C# Boxing and Unboxing Concept. I filled the list of objects with integers and then I wanted to summarize them as result in console output.

List<object> listOfObjects = new List<object>();
//var listOfObjects = new List<object>();

//adding first string to list
listOfObjects.Add("First string");

//adding integers to list
for (int j = 0; j < 5; j++)
{
    listOfObjects.Add(j);
}
listOfObjects.Add("Second string");
for (int k = 5; k < 10; k++)
{
    listOfObjects.Add(k);
}
foreach (var obj in listOfObjects)
{
    Console.WriteLine(obj);
}
var sum = 0;
for (var l = 0;  l < 4;  l++)
{
    sum += (int)listOfObjects[l];            
}
Console.WriteLine(sum);

but output throws exception

Exception thrown: 'System.InvalidCastException' in ConsoleApp.exe An unhandled exception of type 'System.InvalidCastException' occurred

sum += (int)listOfObjects[l] // this unboxing cause compile error

Someone knows why? I used the example from MSDN resource.


Solution

  • Since your listOfObjects is a List whose contents are of type object, you can add anything to it. You first add a string, which is an object. Then you add a bunch of numbers of type int, which is a value type, so the numbers are boxed into an object before they are added to the list. Then you add another string. Then you add another bunch of numbers of type int, again boxing as before.

    Your problem is in the last loop, where you loop over the first 4 elements. The first element is a string, so you cannot cast it to an int.