I want to access members of lists passed in as "object" (the function is handling other data types such as arrays as well). Unfortunately, while this works:
List<object> objectlist = new List<object> { "1", "2" };
object res = ((List<object>)((object)objectlist))[0];
this does not:
List<string> strlist = new List<string> { "1", "2" };
res = (string)((List<object>)((object)strlist))[0];
though it DOES work with arrays.
It does not appear to be possible to convert regular lists to List.
Is using reflection (but with GetMethods to avoid repeated string searches):
MethodInfo info = ((object)list).GetType().GetMethod("get_Item");
object s1 = (object)info.Invoke(((object)list), new object[] { 0 });
the only way to do this?
No, a List<string>
isn't a List<object>
... although it is an IEnumerable<object>
due to generic covariance. However, a List<int>
isn't even an IEnumerable<object>
as covariance doesn't apply to value type type arguments. Fortunately, it is an IEnumerable
.
So to get the first element of an arbitrary object which you know implements IEnumerable
, I'd just use:
object first = ((IEnumerable) source).Cast<object>().First();
(Due to IEnumerator
not implementing IDisposable
, more "manual" ways of doing it end up being a bit fiddly.)
See more on this question at Stackoverflow