[c#] Does Index of Array Exist

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?

This question is related to c# arrays indexing

The answer is


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.


// I'd modify this slightly to be more resilient to a bad parameter
// it will handle your case and better handle other cases given to it:

int index = 25;

if (index >= 0 && index < array.Length)
{
    // Array element found
}

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


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.


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

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

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.


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();
}

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.


You can use LINQ to achieve that too:

var exists = array.ElementAtOrDefault(index) != null;

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.


The answers here are straightforward but only apply to a 1 dimensional array. For multi-dimensional arrays, checking for null is a straightforward way to tell if the element exists. Example code here checks for null. Note the try/catch block is [probably] overkill but it makes the block bomb-proof.

public ItemContext GetThisElement(int row,
    int col)
{
    ItemContext ctx = null;
    if (rgItemCtx[row, col] != null)
    {
        try
        {
          ctx = rgItemCtx[row, col];
        }
        catch (SystemException sex)
        {
          ctx = null;
          // perhaps do something with sex properties
        }
    }

    return (ctx);
}

Examples related to c#

How can I convert this one line of ActionScript to C#? Microsoft Advertising SDK doesn't deliverer ads How to use a global array in C#? How to correctly write async method? C# - insert values from file into two arrays Uploading into folder in FTP? Are these methods thread safe? dotnet ef not found in .NET Core 3 HTTP Error 500.30 - ANCM In-Process Start Failure Best way to "push" into C# array

Examples related to arrays

PHP array value passes to next row Use NSInteger as array index How do I show a message in the foreach loop? Objects are not valid as a React child. If you meant to render a collection of children, use an array instead Iterating over arrays in Python 3 Best way to "push" into C# array Sort Array of object by object field in Angular 6 Checking for duplicate strings in JavaScript array what does numpy ndarray shape do? How to round a numpy array?

Examples related to indexing

numpy array TypeError: only integer scalar arrays can be converted to a scalar index How to print a specific row of a pandas DataFrame? What does 'index 0 is out of bounds for axis 0 with size 0' mean? How does String.Index work in Swift Pandas KeyError: value not in index Update row values where certain condition is met in pandas Pandas split DataFrame by column value Rebuild all indexes in a Database How are iloc and loc different? pandas loc vs. iloc vs. at vs. iat?