views:

96

answers:

2

Hello.

I want to output D:\Learning\CS\Resource\Tutorial\C#LangTutorial But can't work. Compiler error error CS0165: Use of unassigned local variable 'StrPathHead Please give me some advice about how to correct my code or other better solution for my case. Thank you.

static void Main(string[] args)
{
    string path = "D:\\Learning\\CS\\Resource\\Book\\C#InDepth";
    int n = 0;

    string[] words = path.Split('\\');
    foreach (string word in words)
    {

            string StrPathHead;
            string StrPath;
            Console.WriteLine(word);

            if (word == "Resource")
            {
                StrPath = StrPathHead + word + "\\Tutorial\\C#LangTutorial"; 
            }
            else
            {
                StrPathHead += words[n++] + "\\";
            }

    }
}
+3  A: 

Initialize StrPath to the empty string ("") and declare it outside your loop. You may also want to consider using a StringBuilder since Strings in c# are immutable.

Donnie
@Donnie, Thanks for giving `StringBuilder` suggeston to me.
Nano HE
+3  A: 

I agree with Mitch Wheat, but you could solve your current problem initializating StrPath

string StrPath = string.Empty;

And as other people say, declare StrPath outside of the loop.

From MSDN

The C# compiler does not allow the use of uninitialized variables. If the compiler detects the use of a variable that might not have been initialized, it generates CS0165.

Use new to create an instance of an object or assign a value.

Claudio Redi
I'd say set it null;
Preet Sangha