TheLeftExit
TheLeftExit

Reputation: 29

How to use class properties in a predicate that's a property of a class?

My class has the following structure (shrunk an omitted irrelevant parts):

public class MyClass<T>
{
    private T svalue;
    private Predicate<T> spredicate;

    private void Update(T nvalue)
    {
        if(spredicate(nvalue))
            svalue = nvalue;
    }

    public MyClass(Predicate<T> condition){
        spredicate = condition;
    }

    public T Value
    {
        get { return svalue; }
        set { Update(value); }
    }
}

Basically, it stores a value, and only allows changing it if the new value fits a predicate.

I want the following code to work:

var myvar = new MyClass<int>(x => Math.Abs(x - myvar.Value < 10));

However, this doesn't compile because "I'm using a local variable which value wasn't set yet".

In the end, I want to be able to reference a public class property in that predicate. Is there a way to do that?

Upvotes: 0

Views: 296

Answers (1)

If you want your predicate to have a reference to a class instance, pass it in:

public class MyClass<T>
{
    private T svalue;
    private Func<MyClass<T>, T, bool> spredicate;

    private void Update(T nvalue)
    {
        if (spredicate(this, svalue))
            svalue = nvalue;
    }

    public MyClass(Func<MyClass<T>, T, bool> condition)
    {
        spredicate = condition;
    }

    public T Value
    {
        get { return svalue; }
        set { Update(value); }
    }

    public static void Example()
    {
        var myvar = new MyClass<int>((self, newval) => Math.Abs(newval - self.svalue) < 10);
    }
}

We could instead give the predicate a second T parameter instead of MyClass<T>, but then there would be confusion about which parameter is the old value and which is the new one.

Upvotes: 1

Related Questions