gosr
gosr

Reputation: 4708

Foreach loop causes NullReferenceException

At the top of my code (before constructor) I write: String[] CAN = null;

This string array is updated in another function.

Later in my code I have this foreach loop:

foreach (String str in CAN)
{
    if(str.Contains("18FA07FE"))
        cmdResult = true;
    else
        cmdResult = false;
}

I have tried to debug, and at the line of the foreach statement I can see that the CAN string array has successfully been updated, and now contains 1211 elements.

So I don't really know why it's giving me this exception.

Upvotes: 2

Views: 3333

Answers (3)

user474407
user474407

Reputation:

Maybe one of the string value is a null

string [] CAN =  { "first", "second", null, "fourth" };

            foreach ( string str in CAN ) {
                if ( str.Contains( "fourth" ) ) {
                    Console.WriteLine( "Success" );
                }
            }

Upvotes: 2

Hiery Nomus
Hiery Nomus

Reputation: 17779

Where do you get the NullPointer? Is it the loop or the if? I guess your array contains a 'null' element which throws this NPE.

Upvotes: 0

Lasse V. Karlsen
Lasse V. Karlsen

Reputation: 391674

If the problem is only related to the code you've shown, and the code you've described, and it's true that the array has elements, then the only possible explanation is that one of the elements in CAN is a null element, and thus it isn't the foreach itself that throws the exception, but this line:

if (str.Contains(...))
    ^^^
     |
     +-- null

Upvotes: 4

Related Questions