Search code examples
c#syntaxanonymous-methodspredicate

Predicate<int> match question


I do not understand how following code works. Specifically, I do not understand using of "return i<3". I would expect return i IF its < than 3. I always though that return just returns value. I could not even find what syntax is it.

Second question, it seems to me like using anonymous method (delegate(int i)) but could be possible to write it with normal delegate pointing to method elsewere? Thanks

List<int> listOfInts = new List<int> { 1, 2, 3, 4, 5 };
List<int> result =
    listOfInts.FindAll(delegate(int i) { return i < 3; });

Solution

  • No, return i < 3 isn't the same as if (i < 3) return;.

    Instead, it's equivalent to:

    bool result = (i < 3);
    return result;
    

    In other words, it returns the evaluated result of i < 3. So it will return true if i is 2, but false if i is 10 for example.

    You could definitely write this using a method group conversion:

    List<int> listOfInts = new List<int> { 1, 2, 3, 4, 5 };
    List<int> result = listOfInts.FindAll(TestLessThanThree);
    
    ...
    static bool TestLessThanThree(int i)
    {
        return i < 3;
    }