Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Generic interface & implementation issue

Status
Not open for further replies.

link9

Programmer
Nov 28, 2000
3,387
0
0
US
Hello all -

I am having an issue trying to implement a generic interface. Essentially, I have several objects in my library that I need to be able to save their state. So, I created an interface to carry this out. The pertinent bits look like this:
Code:
public interface IStateSaver
{
  ...
  List<T> GetSavedItems<T>(IPrincipal p_User) where T : IStateSaver;
  ...
}
So that any user can just call to an implementer and say "Hey, give me all of my objects" and a list of those objects will be returned.

My problem is coming when I go to implement the interface. I must be missing something on how to use generics properly in this situation. An example implementer looks like this:
Code:
public class Options : IStateSaver
{
   ...
   public List<T> GetSavedItems<T>(IPrincipal p_User) where T : IStateSaver
   {
      List<IStateSaver> output = new List<IStateSaver>();
      ...
      //list population goes here
      ...
      return output;
   }
   ...
}
The compiler is telling me that I:
"Cannot implicitly convert type 'System.Collections.Generic.List<Cmi.Tabulation.IStateSaver>' to 'System.Collections.Generic.List<T>"

Ok, I understand what the message is telling me, but I've used a conditional that says T must be an IStateSaver. So what gives?

What fundamental piece of knowledge am I missing here?

Any input greatly appreciated.

Thanks,
-paul

penny.gif
penny.gif

The answer to getting answered -- faq855-2992
 
<smack>
The solution, of course, is to simply make the method return a List<IStateSaver> if that's what you want, rather than the generic T.
</smack>

The reason that this doesn't work is because of a well documented gotcha of Generics, which is Implicit Type Conversion (or a lack thereof, actually). Here's a link if anyone is interested:


-p

penny.gif
penny.gif

The answer to getting answered -- faq855-2992
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top