Reputation: 39
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
Reputation: 1
public bool Search(int item)
{
return Array.IndexOf(Items, item) > 0 ? true : false;
}
Maybe this would work.
Upvotes: 0
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
Reputation: 4059
Items
need to be intialized , for example in the constructor. E.g. Items = new int[10]
Upvotes: 0
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