tags:

views:

135

answers:

2

I'm trying to use a single Func<T,bool> definition to handle a class and its inheritor. This is what I have:

Func<Job, bool> ValidJob =
        j => !j.Deleted && !j.OnHold && j.PostDate <= DateTime.Now && j.ExpireDate > DateTime.Now;

public class JobExtended : Job { }

So, given that, the following works:

IQueryable<Job> jobs = ...
jobs.Where(ValidJob);

However, the following does not:

IQueryable<JobExtended> jobs = ...
jobs.Where(ValidJob);

I'm wondering if it's possible to have a single Func<T,bool> in this situation and, if so, how? I've tried specifying the type arguments as suggested but am having no luck.

+5  A: 

This will work in C# 4, where delegates have generic covariance and contravariance, but not before that. However, you can use the existing delegate easily from C# 2 onwards:

jobs.Where(new Func<JobExtended, bool>(ValidJob));
Jon Skeet
So simple... thanks!
Jon Freeland
Nice! Didn't know that.
Alexey Romanov
+3  A: 

Here's a variation on the solution: use a generic type in a named function:

public static bool ValidJob<T>(T j) where T : Job
{
    return
        !j.Deleted && 
        !j.OnHold &&
        j.PostDate <= DateTime.Now &&
        j.ExpireDate > DateTime.Now;
}

Then these would work:

IQueryable<Job> jobs = ...
jobs.Where(ValidJob);

IQueryable<JobExtended> jobs = ...
jobs.Where(ValidJob);
Joe Chung
Very nice... thanks for adding this.
Jon Freeland