Iterating over an object that is really a List of arbitrary type

1 day ago 3
ARTICLE AD BOX

You can check against one of the non-generic collection interfaces using the is-operator. I would suggest checking against IEnumerable since that is the most common interface, but ICollection or IList are also alternatives.

if (value is IEnumerable enumerable) { foreach (var v in enumerable){ handleArg(v); } }

I would however be very careful with using this kind of code. You have no type safety, so using code like this code may have unexpected behaviors, and the compiler will not provide any help. It is also require that handleArg can handle any type of object, including other collections, and thus require further type checks. If you do not want to use the type system you might consider just going fully dynamic.

If the list contains value types, like ints or structs, each value will be boxed, causing a lot of allocations and may result in poor performance.

You do not describe what you are trying to do, so it is difficult to provide suggestions about better alternatives. But I would in general recommend to minimize the use of reflection and object as much as possible. A more typical use case would be to check if an object is one of several known types, handle these, and throw an error for any unknown types.

Read Entire Article