C#: Different Ways To Stitch Strings Together

Intro

There is quite a few reasons why you would wanna put strings together in your coding endeavors. Maybe you want to improve the readability of your code, or you want to make one huge string from an array of strings, or you just want to put a string and a variable together.

Improving Readability

Lets say your code looks like this...

    Console.WriteLine("The quick brown fox jumps over the lazy dog, A mad boxer shot a quick gloved jab to the jaw of his dizzy opponent, Jaded zombies acted quaintly but kept driving their oxen forward, Two driven jocks help fax my big quiz");

As you have noticed, the giant long line makes it pretty hard and annoying to read. To make it easier to read you should do this...

Console.WriteLine("The quick brown fox jumps over the lazy dog, "
 + "A mad boxer shot a quick gloved jab to the jaw of his dizzy opponent, "
 + "Jaded zombies acted quaintly but kept driving their oxen forward, "
 + "Two driven jocks help fax my big quiz");

Same code, but one is way more reader friendly.

Making a huge string from an array of strings

Lets say you have an array of strings and you want to stitch them together to make one string(it doesn't have to be huge). This is how you do it...

string[] stringArray = new [] {"make", "one", "long", "string", "from", "an", "array", "of", "strings"};

var hugeString = String.Join(" ", stringArray);

Console.WriteLine(hugeString);

//result
//make one long string from an array of strings

Note that the join method takes a separator as the first argument (in this case a space) and the array to stitch together as the second argument.

Putting together strings and variables

Lets say you have a variable, and you want to put its value within a string. This is how you do it...

Method 1 (string.format)

int mass = 100;
int count = 10;

Console.WriteLine("My {0} pound self ate {1} apples for breakfast.", mass, count);

//result
//My 100 pound self ate 10 apples for breakfast.

Note that while using this method, the order in which you place the variables matters and is zero based.

Method 2 (string interpolation)

int mass = 100;
int count = 10;

Console.WriteLine($"My {mass} pound self ate {count} apples for breakfast.");

//result
//My 100 pound self ate 10 apples for breakfast.

Remember to add the dollar sign ("$") before the string itself.

Conclusion

There you go, those are some of the scenarios that string concatenation can be useful. If you want to learn more about string concatenation check out the C# docs here(string concatenation)

Thanks😁