开发者

Path String Concatenation Question in C#

开发者 https://www.devze.com 2023-01-01 12:13 出处:网络
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

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 += word开发者_高级运维s[n++] + "\\";
            }

    }
}


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消