3

I know I can use an anonymous method or a lambda expression, e.g:

myObjects.RemoveAll(delegate (MyObject m) { return m.X >= 10); });


myObjects.RemoveAll(m => m.X >= 10));

But I cannot figure out whether a regular delegate (delegate bool X (MyObject o) ) could be used, my attempts fail.

I.e. creating a delegate, set it to a method a then pass the delegate instance as the predicate.

John V
  • 4,855
  • 15
  • 39
  • 63
  • This doesn't work, but you can just use a lambda to call the delegate if you need to: `myObjects.RemoveAll(x => myDelegate(x));` (where `myDelegate` is a delegate). – Matthew Watson Aug 13 '18 at 08:51

1 Answers1

2

For compatibility reasons, you must instantiate the delegate explicitly, even if the signature of a different delegate is compatible. This is not very well documented, see discussion in this question.

Example for the (very verbose) syntax do do this:

public void Test()
{
    var l = new List<MyObject>();
    // The following three lines
    var x = new X(my => string.IsNullOrEmpty(my.Name));
    var p = new Predicate<MyObject>(x);
    l.RemoveAll(p);
    // ...will accomplish the same as:
    l.RemoveAll(my => string.IsNullOrEmpty(my.Name));
}

private delegate bool X(MyObject m);

private class MyObject
{
    public string Name { get; set; }
}
Tewr
  • 3,713
  • 1
  • 29
  • 43