This post is based in my original post from yesterday. But I wasn’t precise enough about my needs, so I will try again here.
Please see my current code:
public interface IPosterGenerator<T>
{
IQueryable<T> GetPosters();
}
public class PetPosterGenerator : IPosterGenerator<PetPoster>
{
IQueryable<PetPoster> GetPosters()
{
return busLogic.GetPetPosters();
}
}
public class FlowerPosterGenerator : IPosterGenerator<FlowerPoster>
{
IQueryable<FlowerPoster> GetPosters()
{
return busLogic.GetFlowerPosters();
}
}
public class PinBoard
{
protected List<IPosterGenerator> PosterGenerators { get; set; } // 1. compiler error
public PinBoard(List<IPosterGenerator> generators) // 2. compiler error
{
this.PosterGenerators = generators;
}
public List<BasePoster> GetPosters()
{
var posters = new List<BasePoster>();
foreach (var generator in PosterGenerators)
{
posters.Add(generator.GetPosters());
}
return posters;
}
}
My goal is to create a “PinBoard” which can return a list of posters. Each poster can be of a different type (e.g. pet poster, flower poster, etc.). Every poster has a totally different look, content and so on. But they all inherit from a BasePoster class.
All in all I am going to have about 100 different types of posters. A concrete PinBoard instance can easily contain 1000 posters and more of all different kinds of posters (in diverse order).
In order to populate the posters of a certain PinBoard, I need to feed the PinBoard with a list of certain poster generators (the amount and type of generators will change based on the context). There will be one poster generator per poster type (e.g. the PetPosterGenerator which generates a collection of pet posters).
I thought it would be nice if all my poster generators could share the same (type safe) interface. That’s why I introduced the IPosterGenerator interface.
My problem is that the code does not compile. There are two compiler errors with the same error message: Using the generic type ‘myApp.IPosterGenerator’ requires 1 type arguments
I am not surprised by the error message because I am not defining any type at these locations. It would be great if I could do something like this in the line of the first error:
protected List<IPosterGenerator<T>> PosterGenerators { get; set; }
But when I do this, the compiler can’t find type or namespace T.
Now I am kind of lost. Maybe using the generic IPosterGenerator interface is not such a good idea after all. But I am sure that at some point in my application I need to know or access the concrete poster type which a certain IPosterGenerator represents.
How would you guys approach this? Thank you very much for your support in advance.
There’s no magic solution. If you want to use generics, you still need to use them. I mean that you can’t avoid them.
In the other hand, you can take advantage of covariance in order to let the
IPosterGenerator<T>Tparameter acceptBasePoster:Now you can do this:
So easy! 🙂