I know this is most probably a simple question involving Generics, or, quite possibly, just a big "no-no" overall, but I'm curious to see if I can get this working.
I'm trying to create a method that takes in an object
and, if the object
is an enumerable type, to pass it off to a method that can work on any kind of enumerable, but I'm getting terribly stuck.
My current code for the method that takes in an object looks something like the following:
private void MyMethod()
{
Dictionary<string, object> MyVals = new Dictionary<string,object>();
... fill the MyVals dictionary ...
object x = MyVals["Val_1"];
Type type = x.GetType();
// Check if we have a series of values rather than a single value
if (type != typeof(string) && typeof(IEnumerable).IsAssignableFrom(type))
Test(x);
}
Then, I thought I could write something like one of the following as the method signature for my Test
method:
1. Write it as if it's an IEnumerable of object:
private void Test(IEnumerable<object> MyEnumeration)
Tried calling it via:
Test((IEnumerable<object>)x);
Leads to run-time error that it cannot cast from IEnumerable<int>
to IEnumerable<object>
2. Try using Generics:
private void Test<T>(IEnumerable<T> MyEnumeration)
Tried calling it via:
Test(x);
Leads to design-time error that the signature is incorrect / invalid arguments.
or via:
Test<type>(x);
Leads to a design-time error that the type or namespace type
could not be found.
How could this be done OR is it just bad programming practice and there is a better way to do this?
Thanks!