maplemale
maplemale

Reputation: 2046

Auto-Property Initializes vs Constructor Initializes which takes precedence?

Let's say I'm doing this...

public class Customer
{
    public Customer()
    {
        customerID = Guid.NewGuid();
    }

    public Guid customerID { get; set; } = Guid.NewGuid();
}

...because, I know this is going to occur as my dev team moves to C#6.0. Which is going to take precedence / be used (the constructor NewGuid() or the property NewGuid()) and why? When should we use one vs. the other as a best practice?

Upvotes: 9

Views: 2169

Answers (3)

Xiaoy312
Xiaoy312

Reputation: 14487

It seems that the Auto-property initializer will be the first to be invoked, and then, the constructor.

I made a small demo with LINQPad :

void Main()
{
    new Test().Dump("result");
}

// Define other methods and classes here
class Test
{
    public int MyProperty1 { get; set; } = 1.Dump("auto-prop init");
    public Test()
    {
        MyProperty1 = 2.Dump(".ctor");
        MyProperty2 = 2.Dump(".ctor");
    }
    public int MyProperty2 { get; set; } = 1.Dump("auto-prop init");
}

And, the result is the following :

enter image description here

Upvotes: 5

Evk
Evk

Reputation: 101633

Auto property initializer is basically syntax sugar for this:

private Guid _customerID = Guid.NewGuid();
public Guid customerID
{
    get { return _customerID; }
    set { _customerID = value; }
}

So actual question is: what runs first, field initializers or constructor. And the answer is long time known - field initializers run first, then constructor. So value written in constructor will overwrite value from field initializer in your example.

Upvotes: 21

MichaelChan
MichaelChan

Reputation: 1836

It looks like Autoproperty then constructor. Running this shows 1 as the value which I assume the constructor overwriting the initial value.

public class Customer
{
    public Customer()
        {
            customerID = 1;
        }
    public int customerID { get; set; } = 2;
}

Upvotes: 2

Related Questions