lolsharp
lolsharp

Reputation: 391

Object initzializer/constructor self reference for lambda expression

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?

Upvotes: 2

Views: 1228

Answers (2)

Ivan Fateev
Ivan Fateev

Reputation: 1061

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

Upvotes: 0

Servy
Servy

Reputation: 203830

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

Upvotes: 4

Related Questions