I'm surprised that list.Join()
returns System.Collections.Generic.List`1[System.String]
static void Main(string[] args)
{
var list = new List<string>();
list.Add("1024");
list.Add("2048");
Console.WriteLine(list.Join());
Console.WriteLine(string.Join(", ", list));
Console.ReadKey();
}
with an extension method as
public static class StringExtensions
{
public static string Join(this IEnumerable list)
{
return string.Join(", ", list);
}
}
I don't understand it does not return what I'm expected, with the context of I think I'm so familiar with string.join
and extension methods.
I was thinking internally it would be something like this
static string Join(IEnumerable list)
{
StringBuilder sb = new StringBuilder();
foreach (var item in list)
{
sb.Append(item).Append(", ");
}
return sb.ToString();
}
In the end, I use this version, to support generic and non-generic version.
public static string Join(this IEnumerable list)
{
return Join(list.Cast<object>());
}
public static string Join<T>(this IEnumerable<T> list)
{
return string.Join(",", list);
}
The reason is: the extension method casts the generic List<string>
/IEnumerable<string>
to a non-generic IEnumerable
.
Because of that you this will call this params
overload of string.Join
with a single object here:
public static string Join(this IEnumerable list)
{
return string.Join(", ", list);
}
Since the object is a List<string>
which doesn't override ToString
you will get the type-name as result: System.Collections.Generic.List1[System.String]
You could change your extension method in the following way:
public static string Join(this IEnumerable list)
{
return string.Join(", ", list.Cast<object>());
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With