Take the 2-minute tour ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free, no registration required.

In this chart about the features that are in or out of the next version of Roslyn (specifically, for C#), primary constructors are out, but auto-property initializers are in.

The best use case I've seen for the auto-property initializers is using them in conjunction with the primary constructors, i.e.:

public class Customer(string first, string last)
{
    public string First { get; } = first;
    public string Last { get; } = last;
}

However, without the primary constructor, I don't see a good use case for using auto-property initialization that can't just be performed with a normal backing field, like so:

public class Customer
{
    private string _first = "Foo";
    public string First { get { return _first; } };
}

What is the point of using an auto-property initializer without the primary constructor functionality?

share|improve this question
    
You removed the "Last" in your second sample thus making number of lines look similar. –  Den Oct 20 '14 at 8:28

2 Answers 2

up vote 5 down vote accepted

You don't technically need initializers at all. You can always have a backing property, and you can always do your initialization in (all of) your constructors.

They are a convenience to reduce the ceremony that programmers need to go through to do the "right thing" (use properties for public members, have sane, consistent defaults, make code readable). Because if doing the right thing is easier, people are more likely to actually do it.

share|improve this answer

What is the point of using an auto-property initializer without the primary constructor functionality?

Brevity mostly - if you don't require initialization (beyond the default .NET initialization of fields), auto properties are a good succinct syntax:

public string { get; set; }

Now, in your examples you just have a getter, so without a backing field that can be initialized, yes, these are fairly useless.


You could argue that you could simply expose the field directly, instead of using the property, but then, if you do want to change the field or its access semantics, that's a breaking change.

share|improve this answer
    
You may still be able to do public int Stupid {get;} = 4;... But it still isn't wonderful. –  Magus Oct 13 '14 at 16:34
    
@Magus - true for C# 6.0, but not before. –  Oded Oct 13 '14 at 16:35
1  
Correct, which is what this is about. –  Magus Oct 13 '14 at 16:36

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.