0

To be clear, I'm not asking for the Difference between a field and a property.

Assuming I have just a basic auto-property, with no other access modifiers, what is the difference / advantage of having this:

class Book
{
    public string Title { get; set; }
}

over this:

class Book
{
    public string Title;
}

To the client code using Book, it makes no difference: reads and writes are still done to Book.Title.

What benefits does the Auto Property offer over the simplistic Field?

abatishchev
  • 98,240
  • 88
  • 296
  • 433
SNag
  • 17,681
  • 10
  • 54
  • 69
  • @abatishchev: Not a duplicate. The answer to this very particular case isn't covered in that QA. – SNag Jun 21 '19 at 18:06
  • Hurry up, the boss tells you that now you need to make `Book` implement `INotifyPropertyChanged` so they can use it in an MVVM framework. Which is easier to modify? Which one would (potentially) break code? – Ron Beyer Jun 21 '19 at 18:21
  • https://softwareengineering.stackexchange.com/questions/161303/is-it-bad-practice-to-use-public-fields – Sebastian B Jun 21 '19 at 18:23
  • I agree that question is not a duplicate of this question. However, there are many duplicates of that question which are a duplicate of this question. How about [Property(with no extra processing) vs public field](https://stackoverflow.com/q/1272521/150605), [Advantages for using properties v. fields](https://stackoverflow.com/q/14651533/150605), or, maybe best of all, [Public Fields versus Automatic Properties](https://stackoverflow.com/q/1180860/150605)? (Those questions explicitly define a backing field for their property, but are otherwise the same.) – Lance U. Matthews Jun 21 '19 at 18:30
  • @RonBeyer: I get that the auto-property is a safe design choice for future implementations without breaks. What I was really interested in is the difference it makes in the world of C# -- what is possible with auto-properties over and above the field. The links from BACON's answer shed a lot of light. Thanks! – SNag Jun 21 '19 at 18:40
  • Databinding uses properties not fields – Ňɏssa Pøngjǣrdenlarp Jun 21 '19 at 18:41
  • It isn't just a "safe design choice", if you were given a request like that from your employer changing the field to a property is a breaking change for referenced libraries (even if they don't do anything other than `Book.Title = "xyz"`. Either way the biggest advantage I know of is the ability to set breakpoints, so you can see who is modifying the value and when. – Ron Beyer Jun 21 '19 at 18:43
  • @SNag: sure, reopened. I don't like the accepted answer there but others cover your question pretty much. Correct me if not. – abatishchev Jun 21 '19 at 20:06

0 Answers0