4

I sometimes use {get; set;} in c# becuase I am told that sometimes technologies I am working with require them (linq2sql?)

I'm wondering why sometimes a technology may require a private field with a getter and setter (and thus the shorthand is a nice shortcut) rather than a public field.

I understand that having logic within a getter or setter makes sense, but not so sure on the point of empty ones?

Is the answer the same as this post, if so just tell me so!

What is exactly the point of auto-generating getters/setters for object fields in Scala?

Community
  • 1
  • 1
Chris Barry
  • 4,564
  • 7
  • 54
  • 89
  • Same answer. It lets you *change* these property implementations later without breaking any other code that uses them. You just don't know yet whether you'll ever need to. – Hans Passant Mar 04 '12 at 18:54
  • Those libraries just force you to use good practices. That's not hard to understand, is it? – svick Mar 04 '12 at 19:04
  • I think all these ideas become more relevant in old-style APIs (regular old dlls and sdks) than they do in modern LOB applications. We still find ourselves modifying numerous files when a property gets changed or removed. In a LOB if you have set boundaries around your domains; e.g. Business Domain, Data Access, etc..., what you end up with is with a lot of empty setters and getters that you never need to change for all the reasons named above. Those reasons are valid in theory. It's not so bad with C# but something like Java and C++ it makes the code bloated and a real eye sore. – FernandoZ Sep 29 '21 at 16:35

2 Answers2

2

One reason is Inheritance as your link already points out

One other benefit I can think of is that you can make properties read only by exposing them through public getter. You cannot do this with fields

public String ReadOnlyString {get; private set;}
Haris Hasan
  • 29,856
  • 10
  • 92
  • 122
2

The point is that it it's bad encapsulation to expose private members to users of your class. By using a property, you can expose the information in a way that allows you to change the internal implementation or storage of that value without the interface changing.

E.g. If you decided to store an integer as a byte to save memory internally, then all calling code would have to be recompiled. This is inconvenient even if you own all the source code, but extremely inconvenient if your code us I a library that somebody else is using.

Another common example is that you may later wish to raise an event if the value is changed.

Other reasons are that some clients may look for properties via reflection, but will not look for member fields - for example, the forms editor and property grids do this.

Also, you can make properties virtual, which can't be done with fields.

Or to look at it from another point of view, what reasons can you think of to_not_ use properties.

Jason Williams
  • 56,972
  • 11
  • 108
  • 137