I am trying to create a generic class which new\'s up an instance of the generic type. As follows:
public class HomepageCarousel : List
I'd Probably go for the suggestion from Tony "jon" the Skeet pony but there's another way of doing it. So mostly for the fun here's a different solution (that have the down side of failing at runtime if you forget to implement the needed method but the upside of not having to supply a factory method, the compiler will magically hook you up.
public class HomepageCarousel : List where T: IHomepageCarouselItem
{
private List GetInitialCarouselData()
{
List carouselItems = new List();
if (jewellerHomepages != null)
{
foreach (PageData pageData in jewellerHomepages)
{
T homepageMgmtCarouselItem = null;
homepageMgmtCarouselItem = homepageMgmtCarouselItem.create(pageData);
carouselItems.Add(homepageMgmtCarouselItem);
}
}
return carouselItems;
}
}
public static class Factory
{
someT create(this someT, PageData pageData)
{
//implement one for each needed type
}
object create(this IHomepageCarouselItem obj, PageData pageData)
{
//needed to silence the compiler
throw new NotImplementedException();
}
}
just to repeat my "disclaimer" this is very much ment to serve as a reminder that there can be rather different approaches to solving the same problem they all have draw backs and strengths. One draw back of this approach is that it's part black magic ;)
T homepageMgmtCarouselItem = null;
homepageMgmtCarouselItem = homepageMgmtCarouselItem.create(pageData);
but you avoid the perculiar constructor taking a delegate argument. (but I usually go for that approach unless I was using a dependency injection mechanism to supply the factory class for me. Which insidentally is the kind of DI framework I'm working on in my sparetime ;p)