ArrayList
is an untyped list of objects. Objects you add to
such collection don't need to be homogeneous (it can hold few int
, few float
, few strings and one Cat
). you have to cast object you extract to their proper type (of course because compiler doesn't know how to add int
with object
unless you're using dynamic
):
for (int i = 0; i < arr.Length; i++)
{
sum += (int)inputs [i];
}
That said I'd suggest to use a strongly typed list (for example List<T>
) instead of ArrayList
, like this:
var inputs = new List<int>();
Why? Because with ArrayList
nothing stops you to write (on purpose or because of a bug) this code:
inputs.Add(123);
inputs.Add("123");
inputs.Add(new Version("1.0"));
Obviously this will fail at run-time when wrong object type will be added to your list, this constraint (list of integers) is known at compile-time so it's much better to enforce it. Moreover you'll avoid a cast but performance gain is so small that it'll go unnoticed for sure.