1

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?

1
  • 1
    You removed the "Last" in your second sample thus making number of lines look similar.
    – Den
    Commented Oct 20, 2014 at 8:28

2 Answers 2

6

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.

0

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.

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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