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?
I think you want:
Note the
new()constraint onT. (See MSDN on generic constraints for more information.)If you did need the
Typereference corresponding toT, you’d usetypeof(T)– but I don’t think you need it in this case.