Microsoft vs Mono C# compiler initialisation differences. Is this a bug in Mono?

Hello fellow coders! I have the following code:

using System;
namespace Test
{
    class Test
    {
        public bool A = true;
    }

    class Program
    {
        static void Main(string[] args)
        {
            var test = new Test
            {
                A = false
            };

            Console.WriteLine("test.A = " + test.A);
        }
    }
}

When I compile this C# code into a Visual Studio console executable, I get: "test.A = False". However, in Unity 3.3.0f4 (after I delete the namespace bit and change Console.WriteLine to Debug.Log) I get: "test.A = True"

My question: is this a bug in Mono? (I'd expect the VS behaviour)

I've stumbled upon the same issue (Unity 3.4) but with float/int instead of bool. In this case, if the field initializer sets the value to 1, it's not possible to set it to 0 in the object initializer. Any value other than 0 works and if the initial value is 0, it can be set to 1.

2 Answers

2

Looks like a mono bug, if you use properties instead of public fields it works fine:

using UnityEngine;

public class TestBug : MonoBehaviour
{
    void Start()
    {
        var test = new Testee()
        {
            A = false
        };
        Debug.Log("test.A = " + test.A); // Prints False, as expected.
    }
}

class Testee
{
    private bool a = true;
    public bool A { get { return a; } set { a = value; } }
}

Yeah the property seems to work just fine.

That's true, but I'd like to have a default value for A defined in the class, and then override this sometimes when creating an object. And I cannot set A to its default value in the constructor with an ordinary assignment, because that happens after processing the initialiser list.

Modified my answer - same principle, but uses a backing field instead

I'd like to add that I believe it's a Unity bug (since, if you make a straight Mono project in MonoDevelop and run the same code (obviously with different logging methods), it works as expected.

Indeed, I get the same strange behavior in Unity3D.

using UnityEngine;

public class Test : MonoBehaviour
{
    void Start()
    {
        var test = new Testee()
        {
            A = false
        };
        Debug.Log("test.A = " + test.A); // Prints True, not False as expected.
    }
}

class Testee
{
    public bool A = true;
}

...And the behavior in a VS Console App prints False, not True.

I haven't got the slightest clue what Mike was talking about, but it sounds like a bug to me.

A man with your reputation shouldn't be calling Unity that! :-(

Why, is there an ambiguity somewhere?