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();
}
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.
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.
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)
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