You made two big mistakes here.
First, all local variable should be initialized (for type members, initialization by default is used).
You would need to initialize if as
string res = string.Empty;
but this is not a solution yet.
Your second big mistake is repeated concatenation using the same string. You should never do it. Why? Because strings are immutable
. None of the string functions modify a string, they all create a brand-new string. You never concatenate anything of the same object. Concatenation creates a brand-new string object and copies all the data from two concatenating strings. Many intermediate objects are created; and data is moved back and forth. This is bad for performance.
So, you need to use the mutable representation of string, code
. It is initialized through constructor:
System.Text.StringBuilder sb = new System.Text.StringBuilder();
Also, I forgot to mention that you "concatenate" integer with string (in fact, implicit
call creates a string; than two strings are concatenated). Even though it works, I agree with Maciej (please see our discussions in comment and in comments to his Solution 4): this is a pretty bad practice. The
would also work.
When you explicitly use
, you can control the format of the string output (there are many
methods for all types, with different parameters controlling output format). Besides, it makes your code more explicitly showing what is done.