- parameterless - normal properties
- parameterful - indexers
Why should we excapsulate access to field?
- execute some side effect
- cache some value
- lazily create some internal object
- access in thread safe way
- return value which needs to be calculated on fly
But there are some disadvantages with this :
you have to write a method and users have to call that method.
Another way is to use properties : they can be static, instance, abstract, virtual, with any access specifier, with an interface, however they cannot be overloaded and they cannot have void return type
Properties compile down to methods.
Why not to use Properties :
Because as against fields they break the following assumptions:
- fields are always read and write, not properties
- fields never throw exception
- fields can be passed as out or ref
- field access completes immediately
- field always return same value
- field never has side-effects
- field always works on original object.
Cannot have static indexers
No comments:
Post a Comment