Home > Net >  How to set up T with Base Controller
How to set up T with Base Controller

Time:10-02

I have two classes/controllers inheriting from a BaseController

public class ProductController : BaseController
public class CategoryController : BaseController

Considering these controllers are for individual pages, i need to format a List/IEnumerable of the object (Category or Product), passed in.

In the BaseController class i tried to add a T type but i cant understand how this should be done as the below code either throws errors that T does not exist or the existing Controllers break, if i add T as part of the class declaration BaseController<T>.

Heres the BaseController with the method to carry out this

public class BaseController : SomeController
{
    public List<string> GetDataRefresh(List<T> itemList) // <T> causes an error
    {
        foreach (var item in itemList)
        {

        }
    }
}

So i would like to pass in something like a list of products or categories, this method does the work with the data passed in and returns a list of the same data in a List<string> whether that be product, category or any other type.

How could i declare a T in this instance?

Edit 1

Once the above is working in this manner then in my ProductsController i should be able to do something like

private List<string> RefreshData()
{
   return GetDataRefresh(_ctx.GetProducts()); // GetProducts is List<Product>
}

In the Category Controller it would be

private List<string> RefreshData()
{
   return GetDataRefresh(_ctx.GetCategories()); // GetCategories is List<Category>
}

CodePudding user response:

It seems you need this:

public List<string> GetDataRefresh<T>(List<T> itemList)
{
    foreach (var item in itemList)
    {

    }
}
  • Related