Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to detect if an object is of type generic List and cast to the required type?

I have an extension method for converting a generic list to string.

public static string ConvertToString<T>(this IList<T> list)
{
    StringBuilder sb = new StringBuilder();
    foreach (T item in list)
    {
        sb.Append(item.ToString());
    }
    return sb.ToString();
}

I have an object which is of type object that holds a list; the list could be List<string>, List<int>, List<ComplexType> any type of list.

Is there a way that I can detect that this object is a generic list and therefore cast to that specific generic list type to call the ConvertToString method?

//ignore whats happening here
//just need to know its an object which is actually a list
object o = new List<int>() { 1, 2, 3, 4, 5 };

if (o is of type list)
{
    string value = (cast o to generic type).ConvertToString();
}
like image 870
David Avatar asked May 11 '11 13:05

David


People also ask

How do you find the class object of a generic type?

Pass the class object instead and it's easy. The idea here is that since you can't extract the type parameter from the object, you have to do it the other way around: start with the class and then manipulate the object to match the type parameter.

How do you indicate that a class has a generic type parameter?

A generic type is declared by specifying a type parameter in an angle brackets after a type name, e.g. TypeName<T> where T is a type parameter.


1 Answers

You can achieve that, with lots of reflection (both to find the correct T, and then to invoke via MakeGenericMethod etc); however: you aren't using the generic features, so remove them! (or have a secondary non-generic API):

public static string ConvertToString(this IEnumerable list)
{
    StringBuilder sb = new StringBuilder();
    foreach (object item in list)
    {
        sb.Append(item.ToString());
    }
    return sb.ToString();
}

and

IList list = o as IList;
if (list != null)
{
    string value = list.ConvertToString();
}

(you can also use IEnumerable in the above step, but you need to be careful with string etc if you do that)

like image 182
Marc Gravell Avatar answered Sep 18 '22 16:09

Marc Gravell