[Mono-devel-list] Incorrect interpretation of operator arguments?

Anders Gustafsson anders.gustafsson at cureos.com
Tue Jun 8 12:54:39 EDT 2004

This might be a general C# language question; if that is so, I am sorry 
in beforehand that I have posted the issue in this forum :-)

To follow-up on my bug report (#59694, see 
http://bugzilla.ximian.com/show_bug.cgi?id=59694), I made a simple test 
program, TestClass.cs:

using System;

class TestClass
    private int mX;
    public TestClass(int iX)
        mX = iX;
    public static TestClass operator+(TestClass iLhs, TestClass iRhs)
        TestClass ret = iLhs;
        ret.mX = ret.mX + iRhs.mX;
        return ret;
    public static void Main(string[] args)
        TestClass t1 = new TestClass(10);
        TestClass t2 = new TestClass(20);
        TestClass t3 = t1 + t2;
        Console.WriteLine("t1 is " + Convert.ToString(t1.mX) + ", should 
be 10");
        Console.WriteLine("t2 is " + Convert.ToString(t2.mX) + ", should 
be 20");
        Console.WriteLine("t3 is " + Convert.ToString(t3.mX) + ", should 
be 30");

Upon compiling (mcs TestClass.cs or gmcs TestClass.cs) and running (mono 
TestClass.exe) it, I get the following output (Mono 1.0 Beta 2, Fedora 
Core 2, Linux kernel 2.6.5-1.358):

t1 is 30, should be 10
t2 is 20, should be 20
t3 is 30, should be 30

i.e. t1 is modified in the addition operation t3 = t1 + t2 !

As far as I understand, arguments are passed by value if not explicitly 
specified otherwise (ref, out; see e.g. ECMA-334 C# Language 
Specification, secs. 8.3 and 17.5.1). In fact, according to ECMA-334 
sec. 17.9, operator parameters are required to be value parameters.
And, even if the arguments were passed by reference, I would have 
expected the statement
TestClass ret = iLhs;
in the operator+ method to make a copy of iLhs's value (ECMA-334, sec. 
14.13.1), not make a reference to the same memory location.

Now, this problem is not confined to Mono. I have compiled the same 
source code with Microsoft.NET compiler csc (through Borland C# 
Builder), and I get the same result as with Mono!

So, maybe I am missing something fundamental here. I am grateful for any 
answer or comment that could shed light on issue.

Kind regards,
Anders Gustafsson
Cureos AB

More information about the Mono-devel-list mailing list