views:

499

answers:

9

I've inherited some code at work that has a really bad smell. I'm hoping to find the most painless solution possible.

Is there a way to check if some arbitrary number is a valid element in an array?

Example - I need to check if array[25] exists.

Preferably I would prefer to do this without doing a foreach() through the array to found the rows.

Is there any way to do this, or am I stuck with foreach loop?

+14  A: 

Test the length

int index = 25;
if(index < array.Length)
{
    //it exists
}
Eoin Campbell
Thanks. I can't believe I didn't think of the .Length property!
splatto
+1  A: 

Assuming you also want to check if the item is not null

 if (array.Length > 25 && array[25] != null)
    {
       //it exists
    }
Martin Harris
+5  A: 

What exactly do you mean by "is a valid element"? You could just do:

if (array.Length >= 26)

which would tell you whether 25 is a valid index into the array or not (assuming a 0 lower bound).

If you need to know whether it's non-null or not, just use:

if (array[25] != null)

(or a combination of the two).

If these don't help, please give a more precise meaning of "valid" for your problem.

Jon Skeet
+1  A: 

You can use the length of the array, and see if your arbitrary number fits in that range. For example, if you have an array of size 10, then array[25] isn't valid because 25 is not less than 10.

jean
A: 

You can rather use a List, so you can check the existence.

List<int> l = new List<int>();
l.Add(45);
...
...

if (l.Count == 25) {
  doStuff();
}
int num = 45;
if (l.Contains(num)) {
  doMoreStuff();
}
Jhonny D. Cano -Leftware-
A: 

array.length will tell you how many elements are in an array

Mike Miller
A: 

You could check if the index is less than the length of the array. This doesn't check for nulls or other odd cases where the index can be assigned a value but hasn't been given one explicitly.

JB King
A: 

You can check the length of the array to see if item 25 is valid in the sense of being in the array, then you could use

if (array.Length > 25)
{ 
   if (array[25] != null)
   {
       //good
   }
}

to see if the array item itself has been set.

Colin Desmond
A: 

It sounds very much like you're using an array to store different fields. This is definitely a code smell. I'd avoid using arrays as much as possible as they're generally not suitable (or needed) in high-level code.

Switching to a simple Dictionary may be a workable option in the short term. As would using a big property bag class. There are lots of options. The problem you have now is just a symptom of bad design, you should look at fixing the underlying problem rather than just patching the bad design so it kinda, sorta mostly works, for now.

Wedge