Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

char + char = int? Why?

Tags:

c#

.net

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 chars should be resulting to a string that concatenates the chars, not int?

like image 969
John Isaiah Carmona Avatar asked May 31 '13 07:05

John Isaiah Carmona


People also ask

Why does char char give integer in C#?

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.

What does char int do?

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.

Why do we use char?

The char type is used to store single characters (letters, digits, symbols, etc...).

Is char the same as int?

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 .


1 Answers

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)

like image 147
Dirk Avatar answered Oct 12 '22 01:10

Dirk