views:

124

answers:

3

Hi, 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; });
+11  A: 

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;
}
Jon Skeet
+1  A: 

The return statement will can only return a value as you say. In this example the statement i<3 will first be evaluated to either true or false and boolean value will be returned, it will not return i<3, but the result of the equation.

jweber
A: 

You can also write your example using a lambda expression:

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

Other interesting examples:

var listOfInts = new List<int> { 1, 2, 3, 4, 5 };
var all = listOfInts.FindAll(i => true);
var none = listOfInts.FindAll(i => false);
Douglas