C # - Why doesn't the constructor write an initialized value?

Why does this code not display the value 50?

class Program
{
    static void Main(string[] args)
    {
        var myClass = new TestConstructor() { MyInt = 50 };
    }
}

class TestConstructor
{
    public int MyInt { get; set; }

    public TestConstructor()
    {
        Console.WriteLine(this.MyInt);
        Console.Read();
    }
}
+3
source share
7 answers

This code:

 var myClass = new TestConstructor() { MyInt = 50 };

effectively transforms into:

var tmp = new TestConstructor();
tmp.MyInt = 50;
var myClass = tmp;

How would you expect a property to be set before the constructor runs?

(Using a temporary variable here is not important in this case, but it may be in other cases:

var myClass = new TestConstructor { MyInt = 50 };
myClass = new TestConstructor { MyInt = myClass.MyInt + 2 };

In the second line, it is important that myClass.MyIntyou still refer to the first object, not the newly created one.)

+11
source

This piece of code first creates a class, and then assigns the value 50 to the property MyIntafter execution Console.WriteLine.

+10
source

:

var temp = new TestConstructor();
temp.MyInt = 50;
var myClass = temp;

. , , , :

public TestConstructor(int myInt)
{
    MyInt = myInt;
    Console.WriteLine(MyInt);
}

, :

var myClass = new TestConstructor(50);
+3
source

Your code has been translated as

 var myClass = new TestConstructor(); //Here occures Console.Write(). myInt is 0 now
 myClass.MyInt = 50;
+2
source

Since the syntax you use first creates the object and calls the constructor, and then sets your value.

+1
source

You call the new TestConstructor () and only the second time you have sat this property!

+1
source

When using the initializer of the object you are using, the default constructor is called first, and THEN sets the various properties and fields that you set.

This means that you probably see the value default(int)in the console here, since you are not setting the value in the constructor itself.

+1
source

All Articles