2 Replies - 362 Views - Last Post: 27 September 2017 - 06:13 AM Rate Topic: -----

#1 JapanDave  Icon User is offline

  • D.I.C Regular

Reputation: 29
  • View blog
  • Posts: 366
  • Joined: 01-February 16

Why does concating chars add their ASCII values?

Posted 27 September 2017 - 04:15 AM

What is the reasoning behind char values using their ASCII values?

Ie, in the below code, the first two examples work as they should , but the last one actually adds the ASCII values together.

StringBuilder builder = new StringBuilder();
            string str = "1027";
            char[] ch = str.ToCharArray();
            foreach (var item in ch)
            {
                builder.Append(item);
            }
            Console.WriteLine(builder); 
            //Result is 1027

            var sOne = ch[0];
            
            char sTwo = ch[1];
            
            char sThree = ch[2];
            
            char sFour = ch[3];

            Console.WriteLine(String.Concat(sOne, sTwo, sThree, sFour));
            //Result is 1027

            string newString = (ch[0] + ch[1] + ch[2] + ch[3]).ToString();
            Console.WriteLine(newString);
            //Result is 202
            


I understand that that is what the documentation states, that they default to their ASCII values, but I can't understand why?

This post has been edited by JapanDave: 27 September 2017 - 04:19 AM


Is This A Good Question/Topic? 0
  • +

Replies To: Why does concating chars add their ASCII values?

#2 andrewsw  Icon User is offline

  • the case is sol-ved
  • member icon

Reputation: 6375
  • View blog
  • Posts: 25,756
  • Joined: 12-December 12

Re: Why does concating chars add their ASCII values?

Posted 27 September 2017 - 05:04 AM

FYI You can force concatenation with:

string newString = ("" + ch[0] + ch[1] + ch[2] + ch[3]);

(notice the omission of ToString now)

The operator + is, in effect, overloaded depending on the types of operands. For numbers, it adds. For strings, it concatenates. char's are integer types, so they add.

There are other combinations. The above works because it includes a string.
Was This Post Helpful? 1
  • +
  • -

#3 JapanDave  Icon User is offline

  • D.I.C Regular

Reputation: 29
  • View blog
  • Posts: 366
  • Joined: 01-February 16

Re: Why does concating chars add their ASCII values?

Posted 27 September 2017 - 06:13 AM

Yeah, I figured that out as this also works,

string newString = (ch[0].ToString() + ch[1] + ch[2] + ch[3]);

Was This Post Helpful? 0
  • +
  • -

Page 1 of 1