The default value for the Attach Predicate parameter as a method parameter

I have a method that selects data. It can support multiple use .Where() if the caller can provide a predicate for modifying .Where() . I tried something like

 private class ABJoin { public AA { get; set; } public BB { get; set; } } bool NoFilter(ABJoin join, int index) { return true; // Don't filter at all for this } private IEnumerable<TResult> GetData (Func<ABJoin, int, bool> filter) { var query = ctx.TypeA .Join(ctx.TypeB, a => a.BId, b => b.Id, (a, b) => new ABJoin() { A = a, B = b }) // etc. } 

Works great for now.

However, in some use cases it is not required to provide any filter (the real version has other parameters to distinguish behavior in each case). I thought it would be convenient to provide a default value for the filter parameter

 private IEnumerable<TResult> GetData (Func<ABJoin, int, bool> filter = NoFilter) 

However, this does not compile. The error indicates that NoFilter should be a compile-time constant.

Is there a way to provide a default value for filter in GetData() ?

+1
source share
1 answer

Provide a default value of null and replace it with the real delegate inside the method:

 private IEnumerable<TResult> GetData(Func<ABJoin, int, bool> filter = null) { filter = filter ?? ((a,b) => true); } 
+2
source

All Articles