Bad compiler warnings when using anonymous methods for Predicate<T>

Tags: .NET, C#

I was sitting around munching some code, and needed to filter a list I had:

List<Whatever> list = // get list

outputList = list.FindAll(delegate(Whatever item)
{
   if (// blah blah)
   {
      return true;
   }
   else
   {
   return false
;
   }
}
);

(Ignore the greyed-out text for now).

When compiling, I got a strange error message:
"cannot convert from 'anonymous method' to 'System.Predicate<Whatever>'".

This put me off for a few minutes while I tried checking code samples and such to make sure that this really SHOULD work. Only when I tried explicitly casting the anonymous delegate to a Predicate<Whatever> did I get a proper compiler error:
'System.Predicate<Whatever>': not all code paths return a value'

Turns out my actual syntax error was being caught by the compiler and incorrectly reported.

Just a heads-up, in case it happens to anyone else.
Ladybug bug ID is FDBK50271, if anyone cares.

21 Comments

Comments have been disabled for this content.