Good question. First, properties are actually functions (methods), but a
property may have both a setter and a getter accessor method, which are both
accessed via the Property name. Also, property getters and setters do not
have parameters (except in VB, of course). So, why use a Property instead of
a function?
Well, a property is generally something you treat as if it were a "property"
or "characteristic" or "state" of a class, whereas a method or function is
generally treated as a process, something to do or execute. For example,
System.Windows.Forms.Control has a property called "Height" which is the
height (in pixels) of the Control, a characteristic of the Control. Compare
this to the method OnLoad(EventArgs), which defines a process, something the
Control executes.
Contrast properties with fields in a class. A field is similar to a
variable, but exists at class level. It is a piece of data. A property may
*expose* a field or some data, via its getter and setter accessor methods,
but the methods are processes rather than data. What is the purpose of this
indirection?
There are several purposes. A field can be read to or written from. By
omitting the setter or getter method, a property can be read-only or
write-only. A property may expose a characteristic which is calculated, such
as the Size property of a Control. The Size property is of type
"System.Drawing.Size" and it contains both the Width and Height of the
Control. Rather than storing this data twice, it can be stored as Height and
Width, and exposed as a Size via properties, such as the following:
private int _Height;
private int _Width;
public int Height { get { return _Height; } set { _Height = value; } }
public int Width { get { return _Width; } set { _Width = value; } }
public Size Size
{
get { return new Size(_Width, _Height); }
set
{
_Width = value.Width;
_Height = value.Height;
}
}
There are, as I mentioned, other reasons why properties might be used
instead of fields. The bisc rule of thumb might be expressed as "If it is a
process, expose it as a method; if it is state, expose it as a property".
--
HTH,
Kevin Spencer
Microsoft MVP
Chicken Salad Surgery
What You Seek Is What You Get.
"Kondapanaidu" <kondapanaiduwrote in message
news:eH**************@TK2MSFTNGP04.phx.gbl...
>
Hi,
What is the difference between Properties and functions.
Why dont we go for functions instead of properties.
Regrads
*** Sent via Developersdex http://www.developersdex.com ***