Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is C# order of execution in function call with ref?

So I have just caught this bug in our code:

class A
{
    public int a;
}
var x = new A();
x.a = 1;
A qwe(ref A t) {
    t = new A();
    t.a = 2;
    return t;
}
void asd(A m, A n) {
    Console.WriteLine(m.a);
    Console.WriteLine(n.a);
}

asd(x, qwe(ref x));
asd(x, qwe(ref x));

Is the order of execution in function invocation specified regarding the order of parameters?

What is written here is:

1
2
2
2

Which means that the first parameter's reference is saved before the second parameter's function is invoked.

Is this defined behavior? I could not find specific information on the order of execution in C# lang spec.

like image 775
ditoslav Avatar asked Jan 10 '17 12:01

ditoslav


People also ask

What is meant by C?

noun plural c's, C's or Cs. the third letter and second consonant of the modern English alphabet. a speech sound represented by this letter, in English usually either a voiceless alveolar fricative, as in cigar, or a voiceless velar stop, as in case.

What is C and why it is used?

C programming language is a machine-independent programming language that is mainly used to create many types of applications and operating systems such as Windows, and other complicated programs such as the Oracle database, Git, Python interpreter, and games and is considered a programming foundation in the process of ...

What is C and C++ difference?

Conclusion. In a nutshell, the main difference between C and C++ is that C is a procedural with no support for objects and classes whereas C++ is a combination of procedural and object-oriented programming languages.


1 Answers

C# requires that parameter expressions passed to methods be evaluated left-to-right.

Even though the qwe finishes its work prior to invoking asd, C# has captured the reference to "old" A before invoking qwe in preparation for the call. That is why the first argument of the first invocation of asd gets the "old" A object, before it gets replaced with the new A object inside the qwe call.

like image 139
Sergey Kalinichenko Avatar answered Sep 26 '22 14:09

Sergey Kalinichenko