Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IEnumerable extension method with String.Join returns System.Collections.Generic.List`1[System.String]

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);
}
like image 687
Timeless Avatar asked Sep 28 '17 09:09

Timeless


1 Answers

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>());
}
like image 106
Tim Schmelter Avatar answered Sep 17 '22 01:09

Tim Schmelter