Most of the data in Sitecore ends up stored and passed around as a string, hence we have quite a few helper classes to deal with string values. ListString class helps maintaining a list of strings that is serialized as a string itself. Like this:
“Fred|John|Derek”
What you see above is three strings, “Fred”, “John” and “Derek” serialized to a single string, each string being separated by the pipe ‘|’ symbol. Here’s how to use the ListString to create similar list:
ListString list = new ListString(); list.Add("Fred"); list.Add("John"); list.Add("Derek"); string result = list.ToString(); // -> "Fred|John|Derek"
Now you need to parse it somewhere else:
string rawValue = “Fred|John|Derek”; ListString list = new ListString(rawValue); int count = list.Count; // -> 3 string first = list[0]; // -> "Fred" foreach(string s in list) { // supports enumeration too } list.Add("Mary"); string result = list.ToString(); // -> "Fred|John|Derek|Mary"
Note that the class doesn’t check and escape incoming strings, so it’s your responsibility to make sure the values you pass do not contain a separator symbol.
Sitecore uses ListString alot internally, but it’s always better to use higher level API designed for each specific case, if such exists. A good example of that is MultilistField. So when else ListString can be handy? Whenever you need to pass multiple values as one, such as passing parameters, implementing a new field type that stores multiple values, etc.
Disclaimer The opinions expressed herein are my own personal opinions and do not represent my employer's view in anyway.