Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Auto-Property Initializes vs Constructor Initializes which takes precedence?

Tags:

c#

c#-6.0

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?

like image 418
maplemale Avatar asked Nov 28 '22 23:11

maplemale


1 Answers

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.

like image 50
Evk Avatar answered Dec 15 '22 02:12

Evk