Why do I not need any boxing here

T

Tony Johansson

Hi!

public static void Main()
{
//Here i is boxed. This is easy to understand.
int i = 44;
Object o = i;

ArrayList alist = new ArrayList();
alist.Add(44);

//Here I read the element from the ArrayList using object but where will the
unbox take place ???
// It must be done somewhere either in the foreach or in the WriteLine.
foreach (object o in alist)
{
Console.WriteLine(o);
}


//Here how is it possible to read from the ArrayList when there only exist
object because the int was boxed ?
foreach (int i in alist)
{
Console.WriteLine(i.GetType()); // this is of type System.Int32
Console.WriteLine(i);
}
}

//Tony
 
A

Alberto Poblacion

Tony Johansson said:
public static void Main()
{
//Here i is boxed. This is easy to understand.
int i = 44;
Object o = i;

ArrayList alist = new ArrayList();
alist.Add(44);

//Here I read the element from the ArrayList using object but where will
the unbox take place ???
// It must be done somewhere either in the foreach or in the WriteLine.
foreach (object o in alist)
{
Console.WriteLine(o);
}

Internally, the WriteLine method calls o.ToString() in order to write
the passed object. The ToString method in the object in turn is replaced by
the override of ToString() in the Int32 type. At some point, this method
will need to read the value of the int in order to convert it into String,
and reading the value will requiere to "unbox" the integer. You never see it
because it is done internally, but it needs to be done at some point in the
internal implementation.
 
G

Göran Andersson

Tony said:
Hi!

public static void Main()
{
//Here i is boxed. This is easy to understand.
int i = 44;
Object o = i;

ArrayList alist = new ArrayList();
alist.Add(44);

//Here I read the element from the ArrayList using object but where will the
unbox take place ???
// It must be done somewhere either in the foreach or in the WriteLine.
foreach (object o in alist)
{
Console.WriteLine(o);
}

The object reference is sent to the WriteLine method, which then calls
the virtual method ToString on it. The value is implicitly unboxed to
make the virtual method call.
//Here how is it possible to read from the ArrayList when there only exist
object because the int was boxed ?
foreach (int i in alist)
{
Console.WriteLine(i.GetType()); // this is of type System.Int32
Console.WriteLine(i);
}
}

The foreach loop calls the GetEnumerator method of the list, which
returns an IEnumerator that can be used to read the objects. The loop
code will get each object and try to unbox it as an int. If you have
something in the list that is not an int, you will get an
InvalidCastException.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top