Об'єднання рядків

C#:
Об'єднання рядків

How to: (Як це зробити:)

Here’s how to concatenate strings in C#. Check out these examples:

string hello = "Привіт";
string world = "Світ";
string exclamation = "!";
string greeting = hello + ", " + world + exclamation;
Console.WriteLine(greeting); // Output: Привіт, Світ!

Or, use StringBuilder for better performance with lots of strings:

StringBuilder sb = new StringBuilder();
sb.Append("Привіт");
sb.Append(", ");
sb.Append("Світ");
sb.Append("!");
Console.WriteLine(sb.ToString()); // Output: Привіт, Світ!

Deep Dive (Поглиблений Розбір):

Historically, C# developers used operators like + for simple concatenation. But this gets inefficient with numerous strings – every + creates a new string! That’s where StringBuilder comes in; it’s designed for heavy-duty string assembly, efficiently managing memory and processing.

Alternatives? Absolutely. You’ve got String.Concat(), String.Format(), or even string interpolation since C# 6:

string greeting = $"Привіт, {world}{exclamation}";
// Nice and clean.

Under the hood, concatenation with + or $"" is compiled into String.Concat(). That’s fine for a few strings, but with more, use StringBuilder.

See Also (Дивіться також):