Pablo
Pablo

Reputation: 29519

How to enumerate Object?

I am trying to enumerate Object which is actually enumerable, but the type is stored in Type variable

public Type MyListType { get; set; }
public Object MyList { get; set; }
...
foreach (var item in Convert.ChangeType(MyList, MyListType))
{
...
}

This obviously gives an error because ChangeType still returns Object. How can I cast MyList into enumerable type, particularly of MyListType?

Update:

To be more clear, Object is BindingList<T> type, where T is residing in MyListType.

Upvotes: 0

Views: 513

Answers (2)

Servy
Servy

Reputation: 203819

If the type actually implements IEnumerable you can simply cast it to that:

foreach (object item in (IEnumerable) MyList)
{
    //...
}

If the type has a GetEnumerator method that meets the criteria for foreach, making it enumerable in the conceptual sense, but without actually implementing IEnumerable, then you'll need to use dynamic to defer the problem to the runtime, at which point it will be able to figure out which method to call dynamically.

foreach (object item in (dynamic) MyList)
{
    //...
}

(Note that while this is an interesting academic exercise, I really hope you don't actually have such an object in actual production code; you almost certainly shouldn't be using this solution outside of experimentation.)

Upvotes: 0

Jon Skeet
Jon Skeet

Reputation: 1500135

Well if it's actually enumerable, presumably it implements IEnumerable... so you can just use:

foreach (object item in (IEnumerable) MyList)
{
    ...
}

You're not going to have a better compile-time type for item than object anyway...

Upvotes: 5

Related Questions