I’m about flipped upside down here
What I’m trying to do is create a bit of a factory that works on different types of tickets. So I’ve create an ITicket interface that has a couple signatures like
GetOpen();
GetById(int id);
Now, these methods need to return an instance or a list of instances of the same ticket type, so i thought i’d have the interface look like this
List<ITicket> GetOpen();
ITicket GetById(int id);
So in practice, I hoping to create the factory method like this:
public static List<ITicket> GetOpen(ITicket ticket)
{
return ticket.GetOpen();
}
Ok, now for example, I went back to my class MocRequest and implemented the List GetOpen() method like this:
public List<MocRequest> GetOpen()
{
//implementation grabs a bunch of MocTickets out of the database
and converts them into instances of the MocTicketClass and returns them
}
I get an error saying this isn’t a valid implementation because the return type is MocRequest instead of ITicket. I thought that MocRequest IS A ITicket at this stage, in hindsight I guess it’s a bit circular so it doesn’t work. The return type needs to be MocRequest so that it can still be used.
I’ve experimented with making the interface into something more like ITicket<T> but then I still have to specify the ticket class type in the factory which kind of defeats the purpose.
So the objective here was to create a single static method in the factory that would handle this stuff. Am I going about this right way? How do I make this work? Or am I still stuck making multiple methods to handle them? TIA
MocRequestmay be anITicket, but that doesn’t make aList<MocRequest>aList<ITicket>.If you return a
List<MocRequest>where aList<ITicket>is expected, a user of your API might use the resulting list and add anITicketthat is not aMocRequest. What will theList<MocRequest>do in that case? It will break, right?Therefore, the compiler insists on you returning a
List<ITicket>.In general, it’s not adviseable to return
List<T>, because it’s not evident whether you’re returning a copy of something internal or a reference to the actual internal list. Better declare the return type asIEnumerable<ITicket>, which basically means that you just return the tickets, not a writeable list object. (The user of your API is free to insert those tickets into a list of his/her own.)For more info on how to return the enumeration, we’ll need to get more information about what the tickets look like after being fetched from the DB. Are they in a list or do you construct that list etc.?