String concatenation problem

I’m having an issue concatenating a string using a foreach loop. To get straight to the point, here is the code:

string askName = "ASKNAME";

foreach (ServerClient sc in clients) {
       Debug.Log (";" + sc.clientID + "|" + sc.name);
       askName += ";" + sc.clientID + "|" + sc.name;
}

ServerClient is a class that contains an integer (clientID), and a string (name), and clients is a list of ServerClient. This is part of a server that will send a list of clients to the newly connected client.

When I run this code with 2 or more clients connected, the string that is generated looks something like this:

ASKNAME;firstclientID|firstclientName

where client ID is the id of the first client, and client name is the name of the first client. Regardless of how many elements are in the list of ServerClients, it will always return the same string, despite the fact that the clients is a populated list. Debug.Log will return the expected strings for each individual iteration, for two clients it looks something like this:

;firstclientID|firstclientName
;secondClientID|secondclientName

It is when these individual strings are added to askName that the problem occurs, and the code does not function as expected.

I am very confused as to why the string is concatenated once for the first client, but all subsequent clients are ignored despite the populated list. I would greatly appreciate it if someone could help me understand this issue.

I’m not really sure what;s going on here, but for what it’s worth I mocked this up by making clients a List of Vector2’s (since I don’t have your ServerClient class definition) and used the same code that you posted to print their .x and .y values-- it worked fine on my end.

The string isn’t just getting cut off in formatting, I’m assuming. Sorry for being relatively unhelpful.

I don’t understand your question honestly. But your string should “askName” should be

ASKNAME;firstID|firstName;secondId|secondName

etc. What is askName actually ending up as?

I did a quick test here (StringTest, C# - rextester) and it seems to work fine. Maybe you have a compilaton error somewhere that’s not being displayed.

Thank you for your help, I was hoping it was something I didn’t understand since that’s usually how this sort of thing goes down 99.999% of the time.

Have you tried it with a different Object type than ServerClient? Maybe try running it in a new, blank project?

Try:

string askName = "ASKNAME";

foreach (ServerClient sc in clients) {
       askName += ";" + sc.clientID + "|" + sc.name;
       Debug.Log (";" + sc.clientID + "|" + sc.name + "\n" + askName);
}

Make sure you’ve turned off “Collapse” in the console.

I’m guessing what’s happening is that the code is running several times, and some wrong result is overwriting the correct one.