When I don't know the type of a collection at build time, how can I join it?
Answers (1)
Add AnswerYou might develop a helper method to unbox and join the boxed collection if you don’t know the type.
public string UnboxAndJoin(string separator, object obj) { if (obj is IEnumerable enumerable) { return string.Join(separator, enumerable.Cast<object>()); } else { throw new ArgumentException("Object is not an IEnumerable"); } }
Usage:
object myList = new List<string> { “str1”, “str2” };
Console.WriteLine(UnboxAndJoin(“,”, myList)); // str1,str2