tesicg
tesicg

Reputation: 4053

How to use more generic IEnumerable<T>?

I have the code as follows:

PropertyInfo p_info_keys = obj.GetType().GetProperty("Keys");
IEnumerable<string> keys = (IEnumerable<string>)p_info_keys.GetValue(obj, null);

foreach (string key in keys)
{
    // Some code
}

The problem is this line:

IEnumerable<string> keys = (IEnumerable<string>)p_info_keys.GetValue(obj, null);

Because it can be:

IEnumerable<decimal> keys = (IEnumerable<decimal>)p_info_keys.GetValue(obj, null);

I've tried to use this:

IEnumerable<object> keys = (IEnumerable<object>)p_info_keys.GetValue(obj, null);

But, of course, it doesn't work.

So, how can I use more generic construction that can accept both string and decimal?

Thank you in advance.

Upvotes: 4

Views: 219

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1503449

The simplest approach would be to use the fact that IEnumerable<T> extends IEnumerable:

IEnumerable keys = (IEnumerable) p_info_keys.GetValue(obj, null);

foreach (object key in keys)
{
    ...
}

Of course, you don't then have the type of the key at compile-time, but if you're trying to use the same non-generic code for both cases, then that wouldn't be possible anyway.

Another alternative is to do this in a generic method:

public void Foo<T>(...)
{
    IEnumerable<T> keys = (IEnumerable<T>) p_info_keys.GetValue(obj, null);

    foreach (T key in keys)
    {
        ...
    }
}

Upvotes: 6

Related Questions