When I don't know the type of a collection at build time, how can I join it?

Forums .NETWhen I don't know the type of a collection at build time, how can I join it?
Staff asked 2 years ago

If I don’t know the collection type in .net then how I can join it?

Answers (1)

Add Answer
Umang Ramani Marked As Accepted
Staff answered 2 years ago

You 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

Subscribe

Select Categories