Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Specific(exact) characters from char array to string C#

Tags:

c#

I just saw in one source code something like this:

char[] letters = { 'k', 'n', 'p', 's' };

    for (int d1 = 0; d1 < letters.Length; d1++)
    {
        for (int d2 = 0; d2 < letters.Length; d2++)
        {
            for (int d3 = 0; d3 < letters.Length; d3++)
            {
                for (int d4 = 0; d4 < letters.Length; d4++)
                {
                    string left = ""+ letters[d1] + letters[d2] + letters[d3] + letters[d4];
                }
           }
        }
    }

What I am realy wondering is how exactly is that string strName = "" +.... working. What are these "" for? I looked wherever I could, but didnt find answer. Sorry if answer is very easy, I am new in programming, so I will appreciate your understanding.

like image 645
Kadiyski Avatar asked Feb 17 '26 17:02

Kadiyski


1 Answers

Somewhere in the C# Language Specifications (7.8.4 I think) it is written:

String concatenation:

string operator +(string x, string y);

string operator +(string x, object y);

string operator +(object x, string y);

These overloads of the binary + operator perform string concatenation. If an operand of string concatenation is null, an empty string is substituted. Otherwise, any non-string argument is converted to its string representation by invoking the virtual ToString method inherited from type object. If ToString returns null, an empty string is substituted.

So the + operator between a string and a char converts the char to a string (through the .ToString() method of the char) and concatenates the two.

So for example:

char ch = 'x';

string str = "" + ch;

is "converted" to

string str = "" + ch.ToString();

where ch.ToString() is "x" (with double quotes, so a string)

In the end "" + something is a (safe) way to call .ToString() for something, safe because it handles the case that something == null, by not calling .ToString() and returning an empty string.

In your specific case, you can see that line of code as something like:

string left = "" + letters[d1].ToString();
left = left + letters[d2].ToString();
left = left + letters[d3].ToString();
left = left + letters[d4].ToString();

(in truth it is a little more complex if I remember correctly, because the C# compiler optimizes multiple string concatenations through the use of a single call to string.Concat, but this is an implementation detail, see for example https://stackoverflow.com/a/288913/613130)

like image 106
xanatos Avatar answered Feb 20 '26 07:02

xanatos