0

I used to simulate the VAR VS Dynamic variable and later on i came up to this:

 dynamic s = 2;
   var w = "";
   var d1 = s + " " + "dynamic test 1";
   var d2 = s + 'd' + ' ' + "dynamic test 2";
   String d3 = s + 'k' + ' ' + "dynamic test 2";
   var d4 = 'd' + "dynamic test 2";

To make it simple:

enter image description here

My question is:

why does the char d and k turns to a number and while the d in d4 variable remain on its own value which is d?

Vijunav Vastivch
  • 4,153
  • 1
  • 16
  • 30

4 Answers4

4

Execution is done from left to right. So adding integer first and then character type casts the character into integer and then the output of those is appended to string.

For d4 because there is no integer at start and so character is type-casted to string before append.

Explanation:

the integer value of 'd' is 100

the value of ' ' is 32

Hence 2 + 100 + 32 = 134. Thanks Paulf for the suggestions

Thanks Corak for the detailed explanation. Adding it in answer so it is not missed out.

you have an int value (2) and a char value ('d'). You want to add them together. What would the expected outcome be? "2d" would be a string, so neither an int nor a char. For most people, that would be unexpected so that's no good. What else could happen? 'd' could be imcremented by 2. So the result could be 'f'. But that would only work for very few int values. So it was decided, that int plus char results in int, taking the numeric value of the char. This works for almost every combination of int and char, so that was the chosen behaviour.

On the other hand, you have a char value ('d') and a string value ("test"). You want to add them together. What would the expected outcome be? Getting the numeric value of the char like in int + char would result in "100test" which would be very unexpected. Also, the standard behaviour of object + string (or string + object) is to implicitly turn that into object.ToString() + string. And 'd'.ToString() would be "d" (the string value!). So 'd'.ToString() + "test" results in "dtest", which would also be the expected behaviour. So win/win. ^_^

Aman Seth
  • 196
  • 6
  • For completion of explanation you can add the integer value of 'd' is 100 & the value of ' ' is 32 - hence 2 + 100 + 32 = 134. – PaulF Sep 04 '17 at 09:55
  • This answer is accepted but i need more explaination to some GURU'S why is it happen.. without using `.ToString()` – Vijunav Vastivch Sep 04 '17 at 09:55
  • @reds - `ToString()` is implicitly called, whenever you add something to a `string` (or vice versa). – Corak Sep 04 '17 at 09:59
  • Yeah but my idea is why its turn into that way? and the other turns into char. – Vijunav Vastivch Sep 04 '17 at 10:06
  • 2
    @reds - you have an `int` value (`2`) and a `char` value (`'d'`). You want to add them together. What would the expected outcome be? `"2d"` would be a `string`, so neither an `int` *nor* a `char`. For most people, that would be unexpected so that's no good. What else could happen? `'d'` could be imcremented by `2`. So the result could be `'f'`. But that would only work for very few `int` values. So it was decided, that `int` plus `char` results in `int`, taking the numeric value of the `char`. This works for almost every combination of `int` and `char`, so that was the chosen behaviour. – Corak Sep 04 '17 at 10:14
  • 1
    On the other hand, you have a `char` value (`'d'`) and a `string` value (`"test"`). You want to add them together. What would the expected outcome be? Getting the numeric value of the `char` like in `int + char` would result in `"100test"` which would be *very* unexpected. Also, the standard behaviour of `object + string` (or `string + object`) is to implicitly turn that into `object.ToString() + string`. And `'d'.ToString()` would be `"d"` (the `string` value!). So `'d'.ToString() + "test"` results in `"dtest"`, which would also be the expected behaviour. So win/win. ^_^ – Corak Sep 04 '17 at 10:22
3

because of the precedence of the operators and the chosen overload of the + operator. When you look at this line:

var d2 = s + 'd' + ' ' + "dynamic test 2";

for the first + operator you have an int and a char on the two sides. Here the overload int operator +(int x, int y); of the addition operator is chosen which will add the number and the char (which is implicitly converted into an int because behind the curtains it has a numeric representation of 'd'). There you get a int as result.

PaulF provided the link to the documentation which says to char:

The value of a Char object is a 16-bit numeric (ordinal) value.

this is the reason why the result is a number.

The second + operator is treated in the same manner.

The third+ operator has a string of the other side, so the compiler calls the ToString method implicitly on the int variable and another overload of the addition operator is chosen, namely: string operator +(object x, string y); which concatenates the two.

You can now determine the precedence using ( ). In this line:

var d2 = s + ('d' + (' ' + "dynamic test 2"));

Here the third + operator will be evaluated first, so the concatenation overload will be taken. The result is a string. The second operator will encounter again a string on the right hand side, so it will be the same context again, and again the ToString() method will be called and the char (turning into a string) will be concatenated. When reaching the first operator again the ToString() method will be called (now on the int, turning into a string) will be concatenated.

This post might give further help

EDIT

Here is the overview over all possible Addition operator overloads

In general the choice of the data types is determined the following way:

For an operation of the form x + y, binary operator overload resolution Section 7.2.4 is applied to select a specific operator implementation. The operands are converted to the parameter types of the selected operator, and the type of the result is the return type of the operator.

The documentation states for the string concatenation:

When one or both operands are of type string, the predefined addition operators concatenate the string representation of the operands.

The binary + operator performs string concatenation when one or both operands are of type string.

Community
  • 1
  • 1
Mong Zhu
  • 23,309
  • 10
  • 44
  • 76
  • I accept your answer but how about the blank `' '` char why it turns to number also? – Vijunav Vastivch Sep 04 '17 at 10:00
  • 1
    @reds - because `s + 'd'` results in an `int`. Then it's `int + ' '`. So again, the character to add (`' '`) is implicitly turned into an `int`. – Corak Sep 04 '17 at 10:02
  • @reds - see my comment to Aman's answer which explains the values & the result – PaulF Sep 04 '17 at 10:03
  • 1
    Char is 16bit - https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/char – PaulF Sep 04 '17 at 10:09
  • @PaulF thanks for the link for the documentation and the correction of my comment – Mong Zhu Sep 04 '17 at 10:12
  • @reds because a `' '` blank char is still a `char` which is behind the curtains represented by a number. That is why it is implicitly casted to an `int`. If you would write it as `" "` a string then it will be concatenated with the number – Mong Zhu Sep 04 '17 at 11:04
  • 1
    @reds I found the link to the operator overloads. Have a look at my edit – Mong Zhu Sep 04 '17 at 11:06
2

In order to avoid such errors (adding up integer s and character d which result in s + (int) 'd') use string interpolation (or formatting):

  dynamic s = 2;

  var w = "";
  var d1 = $"{s} dynamic test 1";       // s followed by space and dynamic test 1

  // I've preserved 'd' and 'k' to show absence of the errors
  // More natural code is
  // var d2 = $"{s} d dynamic test 2"; 
  var d2 = $"{s} {'d'} dynamic test 2"; // s followed by space then 'd' character ...

  String d3 = $"{s}{'k'} dynamic test 2";
  var d4 = $"{'d'} dynamic test 2";

  ... 

Edit: In case of C# 5.0- which doesn't support string interpolation try using formatting:

  var d1 = string.Format("{0} dynamic test 1", s);
  var d2 = string.Format("{0} {1} dynamic test 2", s, 'd'); 

  String d3 = string.Format("{0}{1} dynamic test 2", s, 'k');
  var d4 = string.Format"{0} dynamic test 2", 'd');

Do not concatenate strings:

  1. Concatenation is less readable
  2. It prones to errors (+ can be different operations - addition and concatenation)
Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215
0

If I were right,it just like ASCII,every letter corresponds to a number

  • 1
    Not exactly. A character set is a set of mappings between a number and a character, called a codepoint. An encoding determines how the number is stored. It maps a codepoint to one or more code units. Code units are integers stored as bytes. In C#, `char` is a UTF-16 code unit. UTF-16 is one of several encodings of the Unicode character set. (ASCII has had only specialized use in the 3 decades.) – Tom Blodget Sep 04 '17 at 14:13