ArrayList list = new ArrayList();
for (int i = 0; i < list.Count; i++)
{
//If list[i] is empty?
}
Is it possible to check if the value on position [i] is empty? If so, how can this be solved?
ArrayList list = new ArrayList();
for (int i = 0; i < list.Count; i++)
{
//If list[i] is empty?
}
Is it possible to check if the value on position [i] is empty? If so, how can this be solved?
There is no concept of “emptyness” in lists. If you can iterate to an element in a list, that element does exist and there is some value. Now, that value could take different forms to semantically mean it’s “empty” but that really depends on your definition of “emptyness”, and on what values you assigned before to make it empty—since a list element only exists once you assign some value to it.
A common value which could be interpreted as empty would be null, which is a reference to nothing. This is the default value for all reference types so it would make some sense to use this as “empty”. But other values could be equally used here.
In general, instead of putting holes with empty values into your list, you should consider just removing those elements instead. That way, when iterating over your list, you only ever have non-empty elements, and you don’t need to add some check everywhere to handle your special empty value.
for (int i = 0; i < list.Count; i++)
{
//If list[i] is empty?
}
Will only loop the elements that are in the array. You must assign a value to the list by either list.Add(somevalue) or list[i] == somevalue.
If it is not assigned then it does not exist at all. So a list can't have an element that is "empty" because if it is not set then there is no key or value to the element. Like the others answered it can be null though. But null is a value.
By the way i prefer to loop a list with foreach like this
foreach(var item in list) {
// do something here.
}
That way you don't need to do
var item = list[i];
to get the value into a variable. Because it is already set by the loop
It depends what your ArrayList contains. And what you mean by "empty". But it shouldn't be too hard to implement. Here are some suggestions:
for(int i = 0; i<list.Count; i++){
if(list[i] == null){ //for objects
//do something
}
if(list[i].equals("")){ //for empty string
//do something
}
if(list[i].exists){ //for objects you created yourselfs whit a boolean exists-function
//do something
}
}
Might be some syntax errors, but you get the point! :)