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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With