Wednesday, April 08, 2009

C# Properties

There are 2 types of properties :
  1. parameterless - normal properties
  2. parameterful - indexers
Why use properties ? coz working with fields breaks data encapsulation/corrupt data.

Why should we excapsulate access to field?
  1. execute some side effect
  2. cache some value
  3. lazily create some internal object
  4. access in thread safe way
  5. return value which needs to be calculated on fly
To achieve this you may use a method that wraps the field - accessor methods.
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:
  1. fields are always read and write, not properties
  2. fields never throw exception
  3. fields can be passed as out or ref
  4. field access completes immediately
  5. field always return same value
  6. field never has side-effects
  7. field always works on original object.
Compiler might inline property.
Cannot have static indexers

No comments: