Information Technology Reference
In-Depth Information
change from a public data member to the equivalent public property, you
must recompile all code that uses the public data member. C# treats binary
assemblies as first-class citizens. One goal of the language is that you can
release a single updated assembly without upgrading the entire applica-
tion. The simple act of changing a data member to a property breaks
binary compatibility. It makes upgrading single assemblies that have been
deployed much more difficult.
While looking at the IL for a property, you probably wonder about the rel-
ative performance of properties and data members. Properties will not be
faster than data member access, but they might not be any slower. The JIT
compiler does inline some method calls, including property accessors.
When the JIT compiler does inline property accessors, the performance
of data members and properties is the same. Even when a property acces-
sor has not been inlined, the actual performance difference is the negligi-
ble cost of one function call. That is measurable only in a small number of
situations.
Properties are methods that can be viewed from the calling code like data.
That puts some expectations into your users' heads. They will see a prop-
erty access as though it was a data access. After all, that's what it looks like.
Yo u r p r o p e r t y a c c e s s o r s s h o u l d l i v e u p t o t h o s e e x p e c t a t i o n s . G e t a c c e s s o r s
should not have observable side effects. Set accessors do modify the state,
and users should be able to see those changes.
Property accessors also have performance expectations for your users. A
property access looks like a data field access. It should not have perform-
ance characteristics that are significantly different than a simple data
access. Property accessors should not perform lengthy computations, or
make cross-application calls (such as perform database queries), or do
other lengthy operations that would be inconsistent with your users'
expectations for a property accessor.
Whenever you expose data in your type's public or protected interfaces,
use properties. Use an indexer for sequences or dictionaries. All data mem-
bers should be private, without exception. You immediately get support
for data binding, and you make it much easier to make any changes to the
implementation of the methods in the future. The extra typing to encap-
sulate any variable in a property amounts to one or two minutes of your
day. Finding that you need to use properties later to correctly express your
designs will take hours. Spend a little time now, and save yourself lots of
time later.
 
Search WWH ::




Custom Search