Why does C# not define an addition operation for char's?

后端 未结 6 944
感动是毒
感动是毒 2020-12-11 04:07

As the title says. Related to this question.

Why does the following code not work? It seems reasonable logically.

string foo = \'a\' + \'b\'; // Fail         


        
6条回答
  •  一生所求
    2020-12-11 04:21

    To get your chars to "add" up you could do one of several things similar to your original intent:

    string foo2 = 'a' + "" + 'b'; //  Succeeds
    string foo3 = 'a'.ToString() + 'b'.ToString(); // Succeeds
    string foo4 = string.Concat('a', 'b'); // Succeeds
    

    For the foo2 example you give the compiler a clue by dropping in an empty string and force an implicit char to string conversion for each char individually.

    For the foo3 example you use the ToString call on each character to allow the addition of two strings.

提交回复
热议问题