Ben
Ben

Reputation: 39

C# Look for matches in array

Im trying to see if a certain element exists in my array. I have a function where i add elements to my array and a search function that returns true if the element exists. I keep getting Object reference not set to an instance of an object error.

I have a field:

int [] Items;

This is the search function:

public bool Search(int item)
{

    bool isInArray = false;
    for (int i = 0; i < Items.Length; i++) // ERROR HERE
    {
        if (Items[i] == item)
        {
            isInArray = true;
            break;
        }

    }
    return isInArray;


}

This is the add Function:

public void Add(int item)
{

    if (Items == null)
    {
        Items = new int[1];
    }
    else
    {
        Array.Resize<int>(ref Items, Items.Length + 1);
    }
    Items[Items.Length - 1] = item;
}

Upvotes: 1

Views: 120

Answers (5)

Dani
Dani

Reputation: 1

public bool Search(int item)
{
    return Array.IndexOf(Items, item) > 0 ? true : false;
}

Maybe this would work.

Upvotes: 0

Charles Bretana
Charles Bretana

Reputation: 146557

Change

for (int i = 0; i < Items.Length; i++)

to

for (int i = 0; i < (Items?? (Items = new int[0])).Length; i++) 

Upvotes: 0

nakhli
nakhli

Reputation: 4059

Items need to be intialized , for example in the constructor. E.g. Items = new int[10]

Upvotes: 0

outcoldman
outcoldman

Reputation: 11832

Check for null before you will do loop:

public bool Search(int item)
{
    bool isInArray = false;
    if (Items != null)
    {
        for (int i = 0; i < Items.Length; i++) // ERROR HERE
        {
            if (Items[i] == item)
            {
                isInArray = true;
                break;
            }
        }
    }
    return isInArray;
}

Upvotes: 0

nvoigt
nvoigt

Reputation: 77364

Your Items is null as long as you don't add at least one.

Upvotes: 1

Related Questions