How to determine if an object is a general list type and applies to the desired type?

I have an extension method to convert a general list to a 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 that has an object of type that contains a list; the list can be List<string> , List<int> , List<ComplexType> any type of list.

Is there a way to detect that this object is a shared list and therefore is discarded into this type of generic 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(); } 
+7
source share
3 answers

You can achieve this with a lot of reflection (both for finding the correct T , and for calling through MakeGenericMethod , etc.); however: you are not using common functions, so remove them! (or have a secondary non-shared 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 previous step, but you should be careful with string , etc.)

+6
source

Instead of encoding the extension method against IList <T>, you could code it against IEnumerable, then this would be:

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

Then you can check if o IEnumerable:

 object o = new List<int>() { 1, 2, 3, 4, 5 }; if (o is IEnumerable) { string value = ((IEnumerable) o).ConvertToString(); } 
+2
source

Use System.Type to find out if your type is arrat (IsArray) and if it is a generic type (IsGenericType)

0
source

All Articles