Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
540 views
in Technique[技术] by (71.8m points)

c# - char + char = int? Why?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...