2

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.

2
  • 1
    Well, do you know where exactly the exception is occurring? Commented Oct 6, 2011 at 7:31
  • Did you check the contents of your string array?..maybe one of the elements of the array is null. :) Commented Oct 6, 2011 at 7:32

3 Answers 3

4

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
Sign up to request clarification or add additional context in comments.

2 Comments

I agree on that.. .just like i said in my first comment, check the string array. :)
Yeah thanks, it turned out that the very last element of the string array was null. Fixed now, cheers!
2

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" );
                }
            }

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.