How does the runtime tell which is which in this case?

  • Thread starter Thread starter csharper
  • Start date Start date
C

csharper

I have been puzzled by some lamda expressions like this one at

http://msdn.microsoft.com/en-us/library/bb549288.aspx

int[] amounts = { 5000, 2500, 9000, 8000, 6500, 4000, 1500, 5500 };

IEnumerable<int> query =
amounts.SkipWhile((amount, index) => amount > index * 1000);

foreach (int amount in query)
{
Console.WriteLine(amount);
}

/*
This code produces the following output:
4000
1500
5500
*/

Apparently, for this lamda expression:

(amount, index) => amount > index * 1000

the runtime knows that the parameter "index" is the index of the integer array amounts. But why doesn't the runtime take "amount" as the index of theinteger array amounts? Is "index" pre-defined in the .net framework? Very unlikely. Or is it positionally determined?

Any thoughts? Thanks.
 
[...]
Apparently, for this lamda expression:

(amount, index) => amount> index * 1000

the runtime knows that the parameter "index" is the index of the integer array amounts. But why doesn't the runtime take "amount" as the index ofthe integer array amounts? Is "index" pre-defined in the .net framework? Very unlikely. Or is it positionally determined?

Any thoughts? Thanks.

Unnamed arguments in C# (and practically every other mainstream
programming language) are positional. That is, the order in which they
appear determines which value goes with which argument.

If you read the documentation for the method you are calling, found at
http://msdn.microsoft.com/en-us/library/bb549288.aspx, you will see that
the delegate signature for that overload takes two arguments and returns
a bool, where the first argument is the enumeration element, and the
second argument is the index of the source element.

The runtime has nothing to do with it. It's not doing anything special;
it's just passing the arguments to your anonymous method in the order
that the caller specifies, and the caller is passing the index as the
second argument (just as the documentation says it will).

Pete

OK, that's why. Thanks. Indeed, I've seen this pattern in other languages as well, for example, javascript.

Depuzzled.
 
Back
Top