0
[TestMethod]
public void FunctionExtention_CombinePredicates_Should_Avoid_Closure()
{
        var value = 0;
        var predicates = new Predicate<int>[]
        {
            x => x > value
        };

        var result = FunctionExtentions.CombinePredicates(predicates);
        value = 1000;
        Assert.IsTrue(result(2));
}

but this test don't pass, I think I must create local copy using deep copy, but C# don't have standard thing.

public static Predicate<T> CombinePredicates<T>(Predicate<T>[] predicates)
{            
    return item => predicates.All(predicate => predicate(item));
}
Jason Evans
  • 28,906
  • 14
  • 90
  • 154
  • 2
    Can you explain *why* you want to do this? Right now, your code behaves just like the rest of the .NET Framework. You seem to want to break this behaviour and have your code behave differently. – nvoigt Jan 17 '15 at 16:19
  • [this](http://stackoverflow.com/questions/451779/how-to-tell-a-lambda-function-to-capture-a-copy-instead-of-a-reference-in-c) might be a hint that even if you want to do this, it will be hard. Because it's pretty much non-standard in C# (compared to C++ for example). – nvoigt Jan 17 '15 at 16:29
  • this task is designed to learn how to create a local of 100% independent copy of this object –  Jan 17 '15 at 16:32

1 Answers1

0

I'm not sure what you are trying to achieve. In C#, lambda captures are by-reference and you cannot change that. So normally, people create local variables that are copies of their values and pass those:

[TestMethod]
public void FunctionExtention_CombinePredicates_Should_Avoid_Closure()
{
        var value = 0;
        var copy = value;
        var predicates = new Predicate<int>[]
        {
            x => x > copy
        };

        var result = FunctionExtentions.CombinePredicates(predicates);
        value = 1000;
        Assert.IsTrue(result(2));
}

Single closures work that way in C#, I don't see why multiple closures should suddenly work differently. Maybe you can ask those who gave you the task to clarify.

nvoigt
  • 75,013
  • 26
  • 93
  • 142