Generic ICollection and interfaces


A

Allan Ebdrup

I have a public sealed Class A that implements the interface I.
Now I want to pass an ICollection<A> as a parameter to a method that takes a
parameter of the type ICollection<I> but I get the error:

Can't convert from System.Collections.Generic<A> to
System.Collections.Generic<I>

Shouldn't I be able to pass ICollection<A> to a method that takes
ICollection<I> when A implements I ?

Do I really need to cast ICollection<A> to ICollection<I> before passing it?

Kind Regards,
Allan Ebdrup
 
Ad

Advertisements

M

Marc Gravell

Casting won't work...

What you nead is a generic method:

public void SomeMethod<T>(ICollection<T> items)
where T : ISomeInterface
{

}


You should find that you can then call this without specifying the generic
parameter:

ICollection<A> myItems = //TODO; needs A : ISomeInterface
SomeMethod(myItems);

Marc
 
Ad

Advertisements

A

Allan Ebdrup

Marc Gravell said:
Casting won't work...

What you nead is a generic method:

public void SomeMethod<T>(ICollection<T> items)
where T : ISomeInterface
{

}


You should find that you can then call this without specifying the generic
parameter:

ICollection<A> myItems = //TODO; needs A : ISomeInterface
SomeMethod(myItems);

Thanks that did the trick.

Kind Regards,
Allan Ebdrup
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top