Álvaro García
Álvaro García

Reputation: 19356

how to use a function as parameter in extension method?

I have read that is recomended to use functions instead of predicates in the extension methods, so I am trying to do it.

public static void Insert<T>(this ObservableCollection<T> paramOC, T NewElement, Func<T, T, bool> condition)
        {
            //code
        }

I am trying to use in this way:

myOC.Insert(myNewElement, e=>e.Name.CompareTo(myNewElement.Name) > 0));

But I get an error that says that the delete System.Func does not take 1 argument.

However, if I use a predicate intead of the function, it works.

What am I missing?

thank so much.

Upvotes: 0

Views: 519

Answers (2)

Reza
Reza

Reputation: 19843

Your Func<T,T,bool> takes 2 parameters and returns bool

You have two choise

  1. as Selman22 says change it to Func<T,bool>
  2. call it as (e1,e2) => ..

Upvotes: 1

Selman Gen&#231;
Selman Gen&#231;

Reputation: 101681

You need Func<T,bool> (which takes one argument and returns bool), not Func<T,T,bool>

Predicate<T> works because it takes one argument and returns bool, so it matches with the lambda expression.Func<T,T,bool> expects two arguments and returns bool which doesn't match with your expression hence the error.

Upvotes: 3

Related Questions