0

I'm working on my first app, which is designed to be a to do list app. I'm a little new to all this so I hope this question isn't too much of a nuisance. I'm trying to build some code to check a string array for null. Here's the code I have


int checkForNull(string[] a, int arrayNum)
    {
        for (int x = -1; x < arrayNum ; x ++ )
        {
            if (a[x].Length == 0)
                //^^ This is a problem for some reason
            {
                return (x);
            }
        }
        return (-1);
    }

I'm trying to parse an array and return the first integer number that comes back as null. It's part of what I'm using to add new categories to my app. The error I'm receiving comes up on 'if (a[x].Length == 0)' "Array index is out of range". I've also tried 'if (a[x] == null)' but received the same error. Any ideas?

Thanks.

Ciwerk
  • 1
  • 1
  • 3
    If `a[x]` is `null`, then accessing `.Length` would throw an exception. Also `a[-1]` is the problem you currently have. Start at `0` – Patrick Roberts Apr 05 '20 at 17:30
  • Why do you start at -1? – Jasper Kent Apr 05 '20 at 17:31
  • Also "Array index out of range" is because in C# arrays are zero based, meaning they start at 0. – Orel Eraki Apr 05 '20 at 17:31
  • Accessing to any array element must be by means of a non-negative number. – snr Apr 05 '20 at 17:32
  • You might like the [String.IsNullOrEmpty(String) Method](https://docs.microsoft.com/en-us/dotnet/api/system.string.isnullorempty?view=netframework-4.8). – Andrew Morton Apr 05 '20 at 17:32
  • I suspect that this problem would go away if you used a `List` instead of an array. [Array versus List: When to use which?](https://stackoverflow.com/q/434761/1115360) [C# List Examples](https://www.dotnetperls.com/list). – Andrew Morton Apr 05 '20 at 19:15
  • @Ciwerk are you trying to convert strings into integers? – OxQ Apr 05 '20 at 19:23
  • @OxQ I imagine that the OP is looking for the first empty position in the array, so that it can have a new ToDo added there. So a List could be more useful as it would transparently remove the limit on the number of ToDo entries. – Andrew Morton Apr 05 '20 at 20:05

1 Answers1

-1

The code should be:

int checkForNull(string[] a)
{
    for (int x = 0; x < a.Length ; x++ )
    {
        if (string.IsNullOrEmpty(a)) // Covers both cases: null empty
            return x;
    }
    return -1;
}

That said, even though the above explains your error, it's reinventing the wheel. As suggested elsewhere, array has a means for doing this directly:

int checkForNull(string[] a)
{
    return Array.FindIndex(a, string.IsNullOrEmpty);
}
Jasper Kent
  • 3,436
  • 13
  • 19