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

I just saw something like this in one source code:

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];
                }
           }
        }
    }

      

I am really wondering exactly how it works string strName = "" +....

. What are these for ""

? I looked wherever I could but couldn't find an answer. Sorry if the answer is very simple, I am new to programming, so I appreciate your understanding.

+3


source to share


2 answers


Somewhere in the C # Language Specification (7.8.4 I think) it says:

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 the string concatenation operand is NULL, the empty string is replaced. Otherwise, any non-string argument is converted to its string representation by calling the virtual ToString method inherited from the type object. If ToString returns null, the empty string is replaced.

So + operator

between a string

and a char

converts char

to string

(via .ToString()

char method ) and concatenates the two.

So for example:

char ch = 'x';

string str = "" + ch;

      

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 something == null

without calling .ToString()

and returning an empty string.

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

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

      

(in truth, this is a bit tricky if I remember correctly, because the C # compiler optimizes multiple string concatenations with a single call string.Concat

, but that's an implementation detail, see for example fooobar.com/questions/8229 / ... )

+5


source


Simple: the letters [i] are char and are added to the expression to pass it to the string "".

eg. int x = 5;



  string str = ""+x;  // "5" as string.

      

Same for char for string :)

+3


source







All Articles