Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Abstract Generic Method

Tags:

c#

linq

generics

C#, .net 3.5

I am trying to create a base class that has a generic method. Classes that inherit from it should specify the method's type(s).

The premise for this is for creating classes that manage filtering.

So I have:

 public abstract class FilterBase {
   //NEED Help Declaring the Generic method for GetFilter
   //public abstract IQueryable<T> GetFilter<T>(IQueryable<T> query);
 }

 public class ProjectFilter:FilterBase {
   public IQueryable<Linq.Project> GetFilter(IQueryable<Linq.Project> query) {
     //do stuff with query
     return query;
   }
 }

 public class ProjectList {
   public static ProjectList GetList(ProjectFilter filter) {
     var query = //....Linq code...

     query = filterCriteria.GetFilter(query); 

   }

 }

Think it is something simple, but I can't get the syntax right in FilterBase for the GetFilter abstract method.

EDIT

Ideally, would like to keep only the method as generic and not the class. If not possible, then please let me know..

like image 461
B Z Avatar asked Aug 28 '09 20:08

B Z


1 Answers

Make the FilterBase class itself generic.

public abstract class FilterBase<T>
{
    public abstract IQueryable<T> GetFilter(IQueryable<T> query);
}

This would enable you to create your ProjectFilter class like this:

public class ProjectFilter : FilterBase<Linq.Project>
{
    public override IQueryable<Linq.Project> GetFilter(IQueryable<Linq.Project> query)
    {
        //do stuff with query
        return query;
    }
}
like image 172
Mark Seemann Avatar answered Sep 24 '22 01:09

Mark Seemann