Patryk
Patryk

Reputation: 3152

How to check whether reference is set to an object or not

There is an array with 1000 cells. I've put in there 50 object, so there is 950 cells (not used references) left.

I want to loop through 50 objects placed in array, then leave the loop. Right now, loop is entering into array[51] and I'm getting the error:

**Object reference not set to an instance of an object.**

I've tried condition if (array[i] != null) but it doesn't work.

edit: (more code)

for (i = 0; i < 1000; i++)
    {
    if (tablica_postaci[i] != null)
       {
       ...(actions)...
       }
    }

0-49 cells are filled, I haven't touched the rest. Still, there's that error. I want my program not to take the actions after finishing with 50th element

Upvotes: 0

Views: 106

Answers (2)

Abdul Munim
Abdul Munim

Reputation: 19217

Why don't you just use where clause and then loop through the array?

var itemsThatAreNotNull = array.Where(a => a != null);

foreach (var item in itemsThatAreNotNull)
{
    // do whatever you want to do with the item
    Console.WriteLine(item.SomeProperty);
}

Upvotes: 1

daryal
daryal

Reputation: 14919

Here is a sample, you can just call break keyword to go out of the loop.

Company[] companies = new Company[1000];
for (int i = 0; i < 50; i++)
{
    companies[i] = new Company();
}

for (int i = 0; i < companies.Length; i++)
{
     if (companies[i] == null)
           {
               break;
           }

}

Upvotes: 1

Related Questions