Search code examples
c#genericsgeneric-collections

Creating a generic function in c# that only works with specific types


I am trying to create a Generic function that handles either of my 2 models. Note that both of these models have the same exact properties...

For example, in the below code the intellisense has no idea that there is a property called Price in T even though both 'NewProduct' and 'OldProduct' have this property. How can I specify to VS the two Types that I want to be able to pass in? IList<NewProduct>, IList<OldProduct>

public static IList<T> GenericFunction<T>(IList<T> objList)
{
    IList<T> filteredData = objList.Where(p => p.Price > 0));
}

Solution

  • Both types need the same interface or common base class, called here ProductBase. You can then use a generic constraint with the where keyword:

    public static IList<T> GenericFunction<T>(IList<T> objList) 
      where T : ProductBase
    {
        IList<T> filteredData = objList.Where(p => p.Price > 0));
    }
    

    This works, if ProductBase defines a property Price.