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;
}
开发者_C百科
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.
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
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" );
}
}
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.
精彩评论