trialgod
trialgod

Reputation: 302

C# Generic ToString Join if Array or IEnumerable

I have a Generic which hast a string Method. If the Type of the generic is a container (Array, IEnumerable, etc.) their values should be separated by a comma.

public class Test<T>
{
    public T GenericProperty { get; set; }

    public override string ToString()
    {
        string ret;
        if (GenericProperty is Array || GenericProperty is IEnumerable)
        {
            ret = String.Join(",", GenericProperty);
        }
        else
        {
            ret = GenericProperty.ToString();
        }
        return ret;
    }
}

I want to test it by adding a linq expression (Select(x => x.ToString()) to it, but linq isn't available.

When I debug the code above, the if clause is executed properly. But I only get "System.Int32[]" as result.

How can I achieve this?

Upvotes: 2

Views: 705

Answers (3)

tukaef
tukaef

Reputation: 9214

The problem is that string.Join treats GenericProperty as new[] {GenericProperty} not as collection (see params keyword).

Try this code:

string.Join(",", ((IEnumerable)GenericProperty).Cast<object>());

Upvotes: 3

dcastro
dcastro

Reputation: 68680

You're actually using the String.Join overload that takes a string and params object[] as arguments.

You need to cast GenericProperty to IEnumerable<T>.

public class Test<T>
{
    public T GenericProperty { get; set; }

    public override string ToString()
    {
        string ret;
        if ( GenericProperty is IEnumerable)
        {
            IEnumerable en = GenericProperty as IEnumerable;
            ret = String.Join(",", en.Cast<object>());

        }
        else
        {
            ret = GenericProperty.ToString();
        }
        return ret;
    }
}

Upvotes: 3

Dennis
Dennis

Reputation: 37770

Since T hasn't any constraints, this line:

String.Join(",", GenericProperty);

calls this overload:

public static string Join(string separator, params object[] values);

which causes call to GenericProperty.ToString(). You need to call another Join overload, which can be achieved this way:

        if (GenericProperty is IEnumerable)
        {
            ret = string.Join(",", ((IEnumerable)GenericProperty).Cast<object>());
        }

By the way, is Array condition isn't necessary, because Array implements IEnumerable.

Upvotes: 2

Related Questions