3
votes

Im trying to write a generic base class that will allow sub classes to pass up an interface as the type and then have the baseclass call methods on the generic but I cant't work out how to do it...

public class BaseController<T> : Controller where T : IPageModel
{
    public virtual ActionResult Index()
    {
        IPageModel model = new T.GetType();

        return View(model);
    }
}

That doesn't compile, have I got the wrong end of the stick when it comes to generics?

2

2 Answers

6
votes

I think you want:

public class BaseController<T> : Controller where T : IPageModel, new()
{
    public virtual ActionResult Index()
    {
        IPageModel model = new T();
        return View(model);
    }
}

Note the new() constraint on T. (See MSDN on generic constraints for more information.)

If you did need the Type reference corresponding to T, you'd use typeof(T) - but I don't think you need it in this case.

1
votes

You should do as bellow to enable creating instance:

public class BaseController<T> : Controller where T :IPageModel,new()
{
    public virtual ActionResult Index()
    {
        IPageModel model = new T();

        return View(model);
    }

}