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

后端 未结 6 949
感动是毒
感动是毒 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:17

    First off, a word about your deductive process. Your deduction -- that char is converted to int, and therefore there is no addition operator defined on char -- is spot on, so good on you. But I note that the deduction process was unnecessary. You could have simply read section 7.7.4 of the specification, which clearly describes all the built-in addition operators. Briefly, they are int + int, uint + uint, long + long, ulong + ulong, float + float, double + double, decimal + decimal, enum-and-underlying type, delegate combination, string + string, string + object and object + string. (And of course, the lifted-to-nullable versions of those that involve value types.) So yes, there are no addition operators which take chars.

    Second, to answer your "why not?" -- chars are a bit weird. Their storage is that of short integers, but their semantics are those of the characters in a string. So should a char be treated as its integer form, or as a short string? The language designers decided in this case to follow the lead of earlier languages like C and treat chars like integers when doing mathematics on them that does not involve strings. If you want to treat them like short strings, there are any number of ways to convert chars to strings. Appending the empty string, as another answer suggests, unambiguously tells the compiler "this operation is on strings, not on the character's integer value".

提交回复
热议问题