Link to home
Start Free TrialLog in
Avatar of paulwhelan
paulwhelan

asked on

Field vs Property?

Hi
whats the difference between a Field and a Property?

If I can modify a Field through a method then isn't that just the same thing?

Thanks
Paul
ASKER CERTIFIED SOLUTION
Avatar of Carl Tawn
Carl Tawn
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
In short:

public string test = ""; // Field

public string Test { // Property
 get {
  return test;
}
set {
  test = value;
}
}

The advantage from using properties are that you:
A) can define if people are allowed to get/set data (both are optional)
B) can do validation before you set/get the data
C) can perform custom things before data is get/set
Avatar of woigl
woigl

To the example before i would suggest to use the field private, otherwise you give full access outside the class...

private string test = ""; // Field

public string Test { // Property
get {
  return test;
}
set {
  test = value;
}
}

Even internal is the handling of the fields and properties different.

this kind of get and set functions are much better handled compare to own written functions to control get and set.
I agree with woigl that in cases when you want to have fields available to outside the class you should make use of properties instead of public fields.
One more reason for properties is the use of Interfaces.

A Interface can not contain fields, but it can contain Properties.
Also, while we're covering all bases, you need to use properties if you want to support databinding, as WinForms controls can only bind to properties and not directly to fields.
Avatar of paulwhelan

ASKER

Thanks guys!

So I need to use both properties and fields?

Cheers
Yes. Fields are the (usually) data storage that are accessed by the properties.