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
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
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
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
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
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.
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.
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.
ASKER
Thanks guys!
So I need to use both properties and fields?
Cheers
So I need to use both properties and fields?
Cheers
Yes. Fields are the (usually) data storage that are accessed by the properties.
http://blogs.msdn.com/ericgu/archive/2003/11/12/52836.aspx
fields vs properties:
http://www.codecomments.com/archive291-2004-3-162554.html
http://www.gamedev.net/community/forums/topic.asp?topic_id=373545
http://blogs.msdn.com/ericgu/archive/2006/03/19/555235.aspx