Search code examples
c#stringgoto

String is unassigned after Label in c#


I have an issue that I totally not understand:

In the following code, the string path is used. path works in front of the lable, but afterwards its unassigned. Confusingly to me, all other variables work!

Code:

path = @"C:\incidents\jobTransfer";
File.WriteAllLines(path + incident + "\\result_" + incident + ".txt", resultText.ToArray());
End:;
File.WriteAllLines(incident, resultText.ToArray());
File.WriteAllLines(path + incident + "\\result_" + incident + ".txt", resultText.ToArray()); // issue at path in this line

enter image description here

Use of unassigned Variable...

I could reassign the variable after the lable but then i always have to edit 2 lines of code in case of change


Solution

  • Somewhere you have:

    string path;
    

    Make it

    string path = null;
    

    and it fixes your problem.


    Although it's assigned null, the path is not unassigned at the label.

    But, since I come to think of it, maybe you meant:

    string path = @"C:\incidents\jobTransfer";
    

    That way, it is assigned and has a valid value from the beginning.

    See this fiddle:


    example

        string path;
        goto End;
    AnotherLabel:
        path = @"C:\incidents\jobTransfer";
        Console.WriteLine(path);
    End:;
        // issue at path in this line
        Console.WriteLine(path);
    

    fix

        string path = null;
        goto End;
    AnotherLabel:
        path = @"C:\incidents\jobTransfer";
        Console.WriteLine(path);
    End:;
        // no issue at path in this line
        Console.WriteLine(path);
    

    suggestion

        string path = @"C:\incidents\jobTransfer";
        goto End;
    AnotherLabel:
        Console.WriteLine(path);
    End:;
        // no issue at path in this line
        Console.WriteLine(path);
    

    advise

        // don't use labels, due to these kinds of obscurities ;-)