1

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?

James Z
  • 12,209
  • 10
  • 24
  • 44
panoskarajohn
  • 1,846
  • 1
  • 21
  • 37
  • 2
    Could you clarify how much understanding you already have of pass-by-value vs pass-by-reference? You might find this useful: https://jonskeet.uk/csharp/parameters.html – Jon Skeet Oct 12 '19 at 08:43
  • @JonSkeet coming from a cpp background. I understand the concept of reference. I understand c# passes objects by reference by default. Expression is a class should't it be passed by ref by default. – panoskarajohn Oct 12 '19 at 11:45
  • 2
    No, your understanding is incorrect. C# passes all arguments - whether they're references or value type values - by value by default. I strongly recommend that you read the page I linked before. – Jon Skeet Oct 12 '19 at 13:02
  • This has nothing to do with `Expressions` and everything to do with how C# passes arguments and parameters in general. – JLRishe Oct 12 '19 at 16:27
  • @JonSkeet now i understand much better what happens. – panoskarajohn Oct 12 '19 at 17:02

1 Answers1

3

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.

Keith Nicholas
  • 43,549
  • 15
  • 93
  • 156