tags:

views:

81

answers:

3

I’m using an API that has an object that returns IEnumerable<T>, so something like Object.GetEnum<T>.

I have a method that within it will call GetEnum but I want to add to the method’s parameters the ability to pass the parameter type. So for example I want to do:

private void myMethod(apiClass???  apiclass)  
{
IEnumerable< itemType > enumX = ObjectGetEnum< itemType >
}
private void Main()
{
    myMethod(apiClass1);
    myMethod(apiClass2);
}

So as above I don’t know what the parameter type should be in myMethod or how to write the code that gets the enumerator. I tried passing “apiClass”, the class which apiClass1 and apiClass2 inherit from. But then got stuck there on what to do…and I don’t think that really work anyways.

So I’m not sure if I just don’t know how in C# to do this, or if it is even possible, …. or perhaps I’m missing something in the API (or the API is missing something to facilitate this).

Thanks FKC

+5  A: 

Okay, I'm going to take a stab at this, although I'd like the question to be clarified. I suspect you just need to make the method generic:

private void MyMethod<TItem>() where TItem : ApiClass
{
    IEnumerable<TItem> enumX = ObjectGetEnum<TItem>();
}

private static void Main()
{
    MyMethod<ApiClass1>();
    MyMethod<ApiClass2>();
}
Jon Skeet
A: 

Are you trying to access the type parameter of the closed constructed type inside a method? Maybe something like this will work:

using System;

class Foo<T> { }

class Program
{
    static void Main()
    {
     myMethod(new Foo<String>());
    }

    private static void myMethod<T>(Foo<T> foo)
    {
     // use the T parameter in here
    }
}
Andrew Hare
A: 

You need something like this:

private void myMethod<T>()
{
    IEnumerable<T> enumX = ObjectGetEnum<T>();
}
Leandro López