Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

As the title says. Related to this question.

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

string foo = 'a' + 'b'; // Fails with an invalid int -> string conversion

Now, from the above linked question we can infer what is going on here: the compiler is using the implicit char -> int conversion, then adding those values. This leads me to believe that there mustn't be an addition operation defined for chars! Is this true, and if so, why is there none?

EDIT: The general consensus is that it isn't so much that there isn't one defined so much as the one that I expect to be defined isn't.

like image 474
Matthew Scharley Avatar asked Oct 04 '09 14:10

Matthew Scharley


2 Answers

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".

like image 91
Eric Lippert Avatar answered Oct 21 '22 08:10

Eric Lippert


What you are really looking for is this:

string foo = String.Concat('a', 'b');

Which is what the compiler does with the '+' operator on strings anyways.

This is about twice as fast as any String.Format operation.

like image 21
John Gietzen Avatar answered Oct 21 '22 09:10

John Gietzen