Home > OS >  Make Method return Func<> instead of bool
Make Method return Func<> instead of bool

Time:03-29

How can I refactor my method to make it return its bool expression as code and not as a bool directly. I need this for an EF Core query, so it really is important that the code is returned as a delegate.

private static bool AreNotNull(DateTime? dateTime1, DateTime? dateTime2) 
        => dateTime1 != null && dateTime2 != null;

CodePudding user response:

You can do it like so:

private static Func<bool> AreNotNull(DateTime? dateTime1, DateTime? dateTime2)
    => () => dateTime1 != null && dateTime2 != null;

Update: As pointed out you need not evaluate everytime the method is called:

private static Func<bool> AreNotNull(DateTime? dateTime1, DateTime? dateTime2){
    var res = dateTime1 != null && dateTime2 != null
    return () => res;
}

Moreover if you want to filter a IQueryable (cf.) which you have to do if you e.g. want the database to make the filtering you need to return Expression<Func<bool>>:

private static Expression<Func<bool>> AreNotNull(DateTime? dateTime1, DateTime? dateTime2)
    => () => dateTime1 != null && dateTime2 != null;
  • Related