views:

68

answers:

2

Can I pass additional parameters to a predicate function?

I need it in a sorting process actually.

public void Sort(
    Comparison<T> comparison
)

where I would like to use Comparison predicate in this form:

public delegate int Comparison<T>(
    T x,
    T y,
        object extraParameter

)

Is this possible?

Thanks,

+2  A: 

No, but you can do this:

public Comparison<T> MakeComparison<T>(object extraParameter)
{
    return
        delegate(T x, T y) 
        {
            // do comparison with x, y and extraParameter
        }
}
Tim Robinson
@Tim: Thanks Tim! This was a very useful information for me.
burak ozdogan
+1  A: 

Simple capture the variables you need when you declare the predicate. Eg:

int i = 0, j = 10;

array.Sort(x => x > i && x < j ? 1 : -1);
leppie