zoukankan      html  css  js  c++  java
  • C# Why does '+' + a short convert to 44

    I have a line of code that looks like this:

    MyObject.PhoneNumber = '+' + ThePhonePrefix + TheBizNumber;

    Basically, I'm creating a phone number in E164 format and then I assign that string to a string property of an object. ThePhonePrefix is a short that holds the international phone prefix and TheBizNumber is a string that holds the phone number digits.

    Why didn't the compiler bug when I was concatenating a short in the string in the first place? And then why does '+' + 1 equal 44?? This was a pretty hard bug to track because there was no compile error and 44 is the phone prefix for the UK so everything "looked" like it was working because the client-side code just saw a UK number. Why 44?

    Thanks.

    enter image description here


    Answer:

    Why didn't the compiler bug when I was concatenating a short in the string in the first place?

    String concatenation using + sign internally calls string.Concat, which internally calls ToStringon each parameter. Hence no error.

    why does '+' + 1

    You are doing character/numeric arithmetic. 43 being value of + and short/int 1 is 44.

    Because of operator + associativity from left to right it is first character/numeric addition and then string concatenation.

    So it is like:

    MyObject.PhoneNumber = ('+' + ThePhonePrefix) + TheBizNumber;

    You can use "+" to mark it as a string or explicitly call String.Concat like:

    var result = string.Concat('+', ThePhonePrefix, TheBizNumber);
    website:http://stackoverflow.com/questions/29397495/why-does-a-short-convert-to-44
  • 相关阅读:
    搜索回车跳转页面
    登录验证码
    【排序算法】排序算法之插入排序
    PAT 乙级 1044 火星数字 (20 分)
    PAT 甲级 1035 Password (20 分)
    PAT 甲级 1041 Be Unique (20 分)
    PAT 甲级 1054 The Dominant Color (20 分)
    PAT 甲级 1027 Colors in Mars (20 分)
    PAT 甲级 1083 List Grades (25 分)
    PAT 甲级 1005 Spell It Right (20 分)
  • 原文地址:https://www.cnblogs.com/vigorz/p/10499138.html
Copyright © 2011-2022 走看看