You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C#字符串拼接报错:该简单控制台程序为何无法正常运行?

Why Your C# Console App Fails at String Concatenation and Throws Errors

Hey there! Let's walk through the issues in your code that are causing errors and preventing proper string concatenation:

First, here's your code for reference:

using System;
namespace ConsoleApp7
{
    class Program
    {
        static void Main(string[] args)
        {
            string name;
            string all;
            for (int i = 1; i <= 3; i++)
            {
                Console.WriteLine("enter name");
                name = Console.ReadLine();
                Console.WriteLine(name);
                all = string.Concat(all, name);
            }
            Console.WriteLine("all the names are ");
            // Console.WriteLine(s1);
        }
    }
}

Key Problems & Fixes:

  • Uninitialized all variable
    In C#, reference types like string default to null when declared but not initialized. When you first run string.Concat(all, name), you're actually concatenating null with your input name—this will result in a string starting with "null" (e.g., if you input "Bob" first, all becomes "nullBob"). Fix this by initializing all to an empty string:

    string all = string.Empty; // Or string all = "";
    
  • Invalid commented output statement
    The line // Console.WriteLine(s1); references a variable s1 that doesn't exist anywhere in your code. Even if you uncomment it, this will throw a compile error. You need to output the all variable instead to see your concatenated result:

    Console.WriteLine(all);
    

Bonus Optimization Tip:

While string.Concat works for small loops, using StringBuilder is more efficient for repeated string operations (since strings are immutable in C#, each concatenation creates a new string object). Here's how you could refactor it:

using System;
using System.Text; // Don't forget this namespace!
namespace ConsoleApp7
{
    class Program
    {
        static void Main(string[] args)
        {
            string name;
            StringBuilder allNames = new StringBuilder();
            for (int i = 1; i <= 3; i++)
            {
                Console.WriteLine("enter name");
                name = Console.ReadLine();
                Console.WriteLine(name);
                allNames.Append(name);
            }
            Console.WriteLine("all the names are: ");
            Console.WriteLine(allNames.ToString());
        }
    }
}

内容的提问来源于stack exchange,提问作者Roee Bloch

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.30 23:12:35