- Home /
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 ins$$anonymous$$d 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.
Answer by Mike 3 · Apr 20, 2011 at 02:11 PM
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; } } }
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.
$$anonymous$$odified my answer - same principle, but uses a backing field ins$$anonymous$$d
I'd like to add that I believe it's a Unity bug (since, if you make a straight $$anonymous$$ono project in $$anonymous$$onoDevelop and run the same code (obviously with different logging methods), it works as expected.
Answer by Statement · Apr 20, 2011 at 02:18 PM
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! :-(
Your answer
Follow this Question
Related Questions
Bug hunting in the code... 1 Answer
Object initializer Compiler BUG? 1 Answer
my mistake or bug? Unity compiler error 0 Answers
Initialising List array for use in a custom Editor 1 Answer
Bug with Unity Compiler with Lambdas? 0 Answers