In C #, how do field initializers and object initializers interact?

I am primarily a C ++ developer, but I recently worked on a project in C #. Today I came across some behavior that was unexpected, at least for me, when using object initializers. I hope someone here can explain what is happening.

Example A

public class Foo {
    public bool Bar = false;
}

PassInFoo( new Foo { Bar = true } );

Example B

public class Foo {
    public bool Bar = true;
}

PassInFoo( new Foo { Bar = false } );

Example A works as I expected. The object passed to PassInFoo has a Bar for true. However, in Example B, foo.Bar is true, even though it is set to false in the object initializer. What can be caused by the object initializer in example B?

+5
source share
4 answers

, , - , .

:

PassInFoo( new Foo { Bar = false } );

:

var tmp = new Foo();    //Bar initialized to true
tmp.Bar = false;
PassInFoo( tmp );
+3

Unity3d Mono (Mono 2.6.5, Unity3d 4.1.2f1, OSX).

, ValueType, int != 0, (bool)true .. , , (int)0 (bool)false .

:

using UnityEngine;
using System.Collections;

public class Foo1 {
    public bool Bar=false;
}

public class Foo2 {
    public bool Bar=true;
}

public class Foo1i {
    public int Bar=0;
}

public class Foo2i {
    public int Bar=42;
}

public class PropTest:MonoBehaviour {

    void Start() {
        PassInFoo(new Foo1 {Bar=true}); // FOO1: True (OK)
        PassInFoo(new Foo2 {Bar=false});/// FOO2: True (FAIL!)
        PassInFoo(new Foo1i {Bar=42});  // FOO1i: 42 (OK)
        PassInFoo(new Foo2i {Bar=0});/// FOO2i: 42 (FAIL!)
        PassInFoo(new Foo2i {Bar=13});/// FOO2i: 13 (OK)
    }

    void PassInFoo(Foo1 f) {Debug.Log("FOO1: "+f.Bar);}

    void PassInFoo(Foo2 f) {Debug.Log("FOO2: "+f.Bar);}

    void PassInFoo(Foo1i f) {Debug.Log("FOO1i: "+f.Bar);}

    void PassInFoo(Foo2i f) {Debug.Log("FOO2i: "+f.Bar);}
}

un-unity3d OSX Mono 2.10.11 (mono-2-10/2baeee2 Wed Jan 16 16:40:16 EST 2013) :

FOO1: True
FOO2: False
FOO1i: 42
FOO2i: 0
FOO2i: 13

: : bugtracker: https://fogbugz.unity3d.com/default.asp?548851_3gh8hi55oum1btda

+5

Unity Mono.

, , .

! . , , .

+3
source
class Program
{
    static void Main(string[] args)
    {
        PassInFoo( new Foo { Bar = false } );
    }
    public class Foo
    {
        public bool Bar = true;
    }

    public static void PassInFoo(Foo obj)

    {
        Console.WriteLine(obj.Bar.ToString());
        Console.ReadLine();
    }
}

The above code works fine when checked using Framework 3.5 (false is displayed in the console window).

+2
source

All Articles