properties

  • Thread starter Thread starter juzan
  • Start date Start date
J

juzan

hi,
what is the advantage of having properties get and set in your code?
i can assign values to my private variables using methods.
why should i use properties?


any key benefits?
thanx
 
* "juzan said:
what is the advantage of having properties get and set in your code?
i can assign values to my private variables using methods.
why should i use properties?

Properties are used to model attributes of an entity. Methods are used
to model operations the entity can perform. Properties allow you to
perform validation of the value assigned to the property, public
variables don't.
 
juzan said:
what is the advantage of having properties get and set in your code?
i can assign values to my private variables using methods.
why should i use properties?

It's mainly a stylistic convention, but there are a few advantages:

1) Most importantly, if you're creating something that will show up in a
designer (e.g. a Windows or Web Forms control), properties will show up in
the property grid, making it -much- easier for the user to control.

2) Properties reduce clutter. Sure, you could use GetValue and SetValue
methods, but having a Value property instead cuts the number of visible
members in half.

3) Properties have meaning to other programmers. In general, properties
should be used when the operations they perform (e.g. getting or setting the
value of a field) are computationally cheap. Methods should be used when
the operation might be complex. That way, other people using your class (if
any) can tell at a glance which things they can use casually and which they
should be careful with. For example, whenever I see a method named
Get[Something], I know that I should cache that value rather than call the
method repeatedly.

4) Properties let you use some shortcuts. For example, you could do
Value += 1 instead of SetValue(GetValue() + 1). The compiled code will be
much the same, but it looks shorter and cleaner.

5) Properties are useful for code serialization. You can specify a
default value for a property, but not for a method. If the property is
equal to the default value, the designer knows it doesn't need to store the
contents of it, which keeps the code shorter and avoids unnecessary
initialization. For that matter, methods can't be used for serialization
without a hell of a lot of work to begin with.

Properties are integrated pretty tightly with the .NET Framework, so
it's just good form to use them, especially if you intend other people to
use your classes (or maintain apps you've written with them, for example).

Jeremy
 
Back
Top