ceth
ceth

Reputation: 45325

Is it possible to make this method generic

I have a classes which implements some interface:

public interface IMyInterface
{  
    string GetKey();
    void SetData(List<int> data);
}

public class A : IMyInterface { .. }
public class B : IMyInterface { .. }

And I have a methods which gets the collections of this classes and make the same thing:

public void methodA(List<A> items)
{
    foreach(var item in items)
    {     
         // do something with A.GetKey();
         // do something with A.SetData();
    }
}

public void methodB(List<B> items)
{
    foreach(var item in items)
    {     
         // do something with B.GetKey();
         // do something with B.SetData();
    }
}

I would like to make this method generic:

public GenericMethod<T>(T items) where T: IEnumerable
{
    for(var item in items)
    {
        // how can I get the item.GetKey();
    }
}

How can I say to compiler that the elements of T:Inumerable implements IMyInterface and have the method GetKey() ?

Upvotes: 3

Views: 71

Answers (2)

Jcl
Jcl

Reputation: 28272

You can just make your constraint: where T: IEnumerable<IMyInterface>

However you don't even need that, and could just make your parameter an IEnumerable<T>...

Or if you only need that IMyInterface you could just avoid generics completely and pass a IEnumerable<IMyInterface> parameter

By the way: your syntax is all wrong

Here's a fiddle with all three methods

Upvotes: 4

Shoaib Shakeel
Shoaib Shakeel

Reputation: 1557

you can do it like this:

public void GenericMethod<T>(IEnumerable<T> items)
    where T : IMyInterface
{
    for(var item in items)
    {
       // how can I get the item.GetKey();
    }
}

Although in current case you don't really need generics use tihs:

public void GenericMethod(IEnumerable<IMyInterface> items)
{
    for(var item in items)
    {
       // how can I get the item.GetKey();
    }
}

Upvotes: 6

Related Questions