You find the difference between a declaration and an assignment. Declaration with lines like
string match;
just announces to the compiler that you will use the match variable of the type string. Destination with strings such as
match = null;
assigns a null match value.
A language can declare that declarations and assignments should always be separated (I'm not 100% sure, but I believe that older versions of Visual Basic did this), but most languages ββallow you to combine declarations and assignment
string match = null;
means
string match;
C # requires variables to be assigned before they are used. Unlike fields and events, local variables are not automatically assigned to default values, so you need to prove to the compiler that before using match value will have some value. The compiler does not care what the value of match is if this variable has a type string.
In your case, the compiler cannot prove with local analysis that strArr will be nonempty because the compiler does not check the Split code, therefore there is no guarantee that the code will even go into foreach , let's match assignment condition. Because calling Console.WriteLine uses match , and since match cannot be assigned at run time with a string match declaration, the compiler requires you to assign match outside the loop. One way to satisfy this requirement is to use string match = null instead of string match .
Adam mihalcin
source share