R. Devon North R. Devon North - 1 year ago 171
C# Question

Trying to understand strange string concatenation behavior

I have a very simple method that takes a string, breaks it into a char array, then creates a new string from the pieces. However it is performing unexpectedly and I don't understand why? Here is a picture of breakpoint. The input string in this case is "20160622".

Edit: Sorry for the pic. Here is the question in text.

internal class Program
private static void Main()
string test = "20160622";

private static string ConvertDateField(string date)
var temp = date.ToCharArray();
var output = temp[0] + temp[1] + temp[2] + temp[3] + "-" + temp[4] + temp[5] + "-" + temp[6] + temp[7] + " 00:00:00";

return output;

The output is "201-06-22 00:00:00".

Edit2: I understand there are probably better ways to do this. What I am trying to understand is why this code is functioning the way it is. ie. why is the 6 the only char not being concatenated?

enter image description here

As you can see, the fourth char, temp[3] which is a '6', is not being concatenated into the output string. Why?

Answer Source

For your question. The char concat is not a string concat. What happened is that c# is doing Math operation for the chars by casting them to int with ASCII.

The corresponding ascii for temp 1, 2, 3, 4 are 50, 48, 49, 54 which the sum is 201. (what an coincidence)

and then int + string concat resulted in string so the rest of the string worked as expected.

There is an easier way to perform the convert if it was a DateTime object. You can simply call dateTime.ToString("yyyy-MM-dd 00:00:00") and you will get the result you want.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download