Why is adding two char
in C# results to an int
type?
For example, when I do this:
var pr = 'R' + 'G' + 'B' + 'Y' + 'P';
the pr
variable becomes an int
type. I expect it to be a string
type with a value of "RGBYP"
.
Why is C# designed like this? Wasn't the default implementation of adding two char
s should be resulting to a string
that concatenates the char
s, not int
?
The interesting thing is that you're not actually adding char s, since C# doesn't define a built-in + operator for the type. However, char is implicitly convertible to int , so the compiler chooses the int version of the + operator when doing overload resolution.
char: The most basic data type in C. It stores a single character and requires a single byte of memory in almost all compilers. int: As the name suggests, an int variable is used to store an integer. float: It is used to store decimal numbers (numbers with floating point value) with single precision.
The char type is used to store single characters (letters, digits, symbols, etc...).
Size of an int is 4 bytes on most architectures, while the size of a char is 1 byte. Note that sizeof(char) is always 1 — even when CHAR_BIT == 16 or more .
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With