What is the difference between , and + while concatenating?

前端 未结 3 771
傲寒
傲寒 2021-01-29 15:41

I have been coding with c# for a last couple of months now, but every time I concatenate I always get confused between the difference between the comma , and the pl

3条回答
  •  野的像风
    2021-01-29 16:20

    As everybody else told you, the , never concatenates. But it is used to pass parameters to functions that do the concatenation.

    I got this exact same question from one of my developers ones. After some discussions I realized that he believed that the , was concatenating before calling the function, and passing only one string as parameter. He though that way simply because he did not know that it is possible to build functions that accepts a variable number of arguments.

    Here you can see how I used the params keyword to tell C# that should accept a variable number of string arguments. That is what Console.WriteLine() is actually doing

     // ConcatenateStrings("multiple", "strings", "are", "passed", "as", "parameters");
     public string ConcatenateStrings(string firstString, params string[] restOfTheStrings)
     {
         // This code is an example only. It is not optimal
         foreach(string oneString in restOfTheStrings)
         {
             firstString += oneString;
         }
         return firstString;
    }
    

提交回复
热议问题