Why bother with properties?
The first question, why even consider properties as a replacement of public fields?- Encapsulation. When you declare a public field on a type you allow everyone to set its value whenever they want, unless the field is readonly, of course. But what happens if you decide to change the logic of setting it to include some sort of a check, for instance? You would have to add a getter and setter methods and make the field private, which breaks your API. This applies to protected fields too.
- Data-binding. Not having to set all UI components manually to a new value whenever you obtain it, but rather let them to change automatically when the source changes, is a huge advantage. You can’t bind to a field, period.
Concerned about performance?
An auto-property is translated into a private backing field with a getter method and a setter method by the C# compiler.public int Number { get; set; } // is translated into private int number; public int Number { get { return number; } set { number = value; } } // and getter and setter are nothing else but int get_Number() { return number; } void set_Number(int value) { number = value; }
“This sure involves a performance penalty, right? A field is just a fiield and it’s accessed directly whereas a property is a field accessed through methods – an extra level of indirection.”
It sure looks like what you think, but the JIT compiler is very clever about this and optimizes it away. How? It’s out of the scope of this article, but I’ll get to it someday. For those eager of you, it’s called inlining.
Writing a property is slower!
You might think that, but did you know that there are code-snippets in VS for different kinds of properties? Try writting prop and press Tab or Enter in order to generate an auto-property and then simply change its type (followed by pressing Tab or Enter) and name. Follows a list of other property code-snippets available in VS:- propg – auto-property with a private setter
- propfull – property in the expanded form
- propdp – dependency property
- include some getter or setter logic or
- have a truly readonly property (auto-property with a private setter in not readonly).
// auto-property initializers public int Number { get; set; } = 10; // getter-only auto-properties public int Number { get; } = 10;
These two new features combined make a huge difference in resulting number of lines of code. There’s no reason to write
public readonly int number = 10;
anymore, because it simply does not offer any benefits over a property. There may be some scenarios where a public field makes more sense, but I’m not aware of any. If you are, feel free to comment.
No comments:
Post a Comment