2

I have a simple filter class looking like this:

public class DateFilter
{
    public DateTime Value { get; set; }

    public Func<FilterObject, bool> Match { get; set; }
}

Is it possible to initialize the Match function in the constructor or the object initializer using the local Value?

Example with assignment after filter creation:

var df = new DateFilter();
df.Match = (input) => df.Value > input.Date;

Is it possible to reduce the example to one statement?

lolsharp
  • 391
  • 4
  • 16

2 Answers2

4

No, you cannot reference a variable in the initializer for that variable. You can only reference it after it has been defined.

Servy
  • 202,030
  • 26
  • 332
  • 449
0

It's not possible, but I can suggest adding one more argument to func, if it fits to your requirements

public class DateFilter
{
    public DateTime Value { get; set; }

    public Func<FilterObject, DateTime, bool> Match { get; set; }

    public DateFilter(Func<FilterObject, DateTime, bool> predicate)
    {
        Match = predicate;
    }
}

var df = new DateFilter( (input, val) => val > input.Date));

Assuming you will pass DateFilter's Value as the second arg of Match

Ivan Fateev
  • 1,032
  • 1
  • 10
  • 26