Search code examples
c#linqlambdaexpressionlinqkit

Filter needs to be passed by reference in order to append to it


I want to understand why the Expression<Func<SomeObject, bool>> filter needs to be passed by reference.

This is an object and should by default be passed by ref in c#.

Expression<Func<SomeObject,bool>> filter = PredicateBuilder.New<SomeObject>(true);


//Function that builds the filter
void buildFilter(ref Expression<Func<SomeObject, bool>> filter){ 
filter = filter.And(x => x.SomeProperty == sth);
...builds filter. }

what this is and why we need to handle it like this?


Solution

  • This is because you are replacing the original object, not changing it. You are making filter point at a new reference by generating it from an existing one.

    filter = filter.And(x => x.SomeProperty == sth);
    

    This doesn't change the object filter points at, it points it at a new one. If you didn't pass by reference, filter would keep pointing at the original object.