Are parameters evaluated in order when they passed into a method?
For Java it's always true, for C it isn't, but what is the answer for C#?
Sample
string.Format("byte1={0} byte2={1} byte3={2}", getNextByte(), getNextByte(), getNextByte()); int pos=0; byte[] arr=new byte[] {1,2,3,4,5,6}; byte getNextByte() { return arr[pos++]; }
This sample works, but is it only luck or a rule?
We pass different arguments into some functions. Now one questions may come in our mind, that what the order of evaluation of the function parameters. Is it left to right, or right to left? To check the evaluation order we will use a simple program. Here some parameters are passing. From the output we can find how they are evaluated.
Information can be passed to methods as parameter. Parameters act as variables inside the method. Parameters are specified after the method name, inside the parentheses. You can add as many parameters as you want, just separate them with a comma. The following example has a method that takes a String called fname as parameter.
As in the case of base types, when a reference to an object is passed to a method, this reference is copied to the formal parameter of method. This means that the formal parameter in the method contains exactly the same value as the argument that was passed to the method.
This is typically easier to update/maintain, clearer to read, and removes the necessity for worrying about ordering. Also, too many parameters for a method is a code smell and there are common refactoring patterns you can follow to help correct it.
Yes, expressions passed as arguments to methods are always evaluated from left to right.
From the C# 4.0 Language Specification:
7.5.1.2 Run-time evaluation of argument lists
During the run-time processing of a function member invocation (§7.5.4), the expressions or variable references of an argument list are evaluated in order, from left to right, [...]
As others have pointed out, the language specification requires that parameters be evaluated in left-to-right order.
However, full disclosure, we accidentally and not on purpose introduced a couple of bugs in C# 4.0 where certain scenarios involving named arguments, optional parameters and ref-omitted parameters in calls to legacy COM objects, such that in those scenarios the side effects of arguments might not be evaluated in strictly left-to-right order. The analyzer that deals with the interactions between those features is complicated and it had some bugs.
I apologize for the errors; we hope to have them fixed in the next version.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With