char + char = int? Why?
Solution 1:
Accoding to the documentation of char it can be implicitly converted into integer values. The char
type doesn't define a custom operator +
so the one for integers is used.
The rationale for there being no implicit conversion to string is explained well in the first comment from Eric Lippert in his blog entry on "Why does char convert implicitly to ushort but not vice versa?":
It was considered in v1.0. The language design notes from June 6th 1999 say "We discussed whether such a conversion should exist, and decided that it would be odd to provide a third way to do this conversion. [The language] already supports both c.ToString() and new String(c)".
(credit to JimmiTh for finding that quote)
Solution 2:
char
is a value type, meaning it has a numerical value (its UTF-16 Unicode ordinal). However, it is not considered a numeric type (like int, float, etc) and therefore, the + operator is not defined for char.
The char
type can, however, be implicitly converted to the numeric int
type. Because it's implicit, the compiler is allowed to make the conversion for you, according to a set of rules of precedence laid out in the C# spec. int
is one of the first things normally tried. That makes the +
operator valid, and so that's the operation performed.
To do what you want, start with an empty string:
var pr = "" + 'R' + 'G' + 'B' + 'Y' + 'P';
Unlike the char type, the string type defines an overloaded + operator for Object, which transforms the second term, whatever it is, into a string using ToString()
before concatenating it to the first term. That means no implicit casting is performed; your pr
variable is now inferred as a string and is the concatenation of all character values.