How to use more general 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 could be:

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

I tried using this:

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

But of course this will not work.

So, how can I use a more general construct that can accept both a string and a decimal?

Thanks in advance.

+4
source share
1 answer

The easiest approach is 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 should not have the key type at compile time, but if you try to use the same non-generic code for both cases, then this will be impossible.

Another alternative is to create a generic method:

 public void Foo<T>(...) { IEnumerable<T> keys = (IEnumerable<T>) p_info_keys.GetValue(obj, null); foreach (T key in keys) { ... } } 
+6
source

All Articles