tags:

views:

62

answers:

2

Hello,

I'm trying to convert a generic value into an array of generic values so that I can comma delimit them. However, I can't convert from my generic type into an array of generic types. hopefully some code will help make things clearer...

    public T Item
    {
        get { return item; }
        set { item = value; }
    }

    public string GetItemAsString()
    {
        string itemString = Item.ToString();

        if(Item.GetType().IsArray)
        {
            itemString = string.Join(",", Item);
        }

        return itemString;
    }

Can someone point me in the right direction?

Thanks.

A: 

Im not exactly sure if this is what your trying to do but you could try something like this.

public T Item 
{ 
    get { return item; } 
    set { item = value; } 
} 

public string GetItemAsString() 
{ 
    string itemString = Item.ToString(); 

    if(Item.GetType().IsArray) 
    { 
        itemString = String.Join(",", (Item as IEnumerable<object>).Select(item => item.ToString()).ToArray());
    } 

    return itemString; 
}
Richard Friend
In .NET 4 you don't need the `ToArray`, as `String.Join` can handle `IEnumerable<T>` directly.
Joel Mueller
A: 

Maybe something like this?

public class Tester<T, R> where T : IEnumerable<R>
{
    private T _item;
    public T Item
    {
        get { return _item; }
        set { _item = value; }
    }

    public string GetItemAsString()
    {
        IEnumerable<R> items = _item as IEnumerable<R>;
        if (items != null)
        {
            StringBuilder str = new StringBuilder();
            int count = 0;
            foreach (R item in items)
            {
                str.Append(count++ > 0 ? "," : String.Empty);
                str.Append(item.ToString());
            }

            return str.ToString();

        }
        return null;
    }
}
mdm20
I wish I could get around having 'R' but I think it's the only way.
paulio