Exitos
Exitos

Reputation: 29740

How do I get the type from this generic situation?

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

Answers (2)

Jon Skeet
Jon Skeet

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

Saeed Amiri
Saeed Amiri

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

Related Questions