Reputation: 29740
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?
Upvotes: 3
Views: 85
Reputation: 1503140
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.
Upvotes: 6
Reputation: 22565
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);
}
}
Upvotes: 1