Possible Duplicate:
C#: Public Fields versus Automatic PropertiesDuplicate? I think not:
This question is not the same as "Why use properties instead of public field". A property with a specified getter and setter is far different than a public field. My question was, is a property WITHOUT a getter and setter, any different.
With the somewhat recent ability to have empty getters and setters, what is the benefit of using them instead of just declaring a public member variable?
Example:
public string MyProperty { get; set; }
versus:
public string MyProperty;
The main difference between making a field public vs. exposing it through getters/setters is holding control over the property. If you make a field public, it means you provide direct access to the caller. Then, the caller can do anything with your field, either knowingly or unknowingly.
It is a good practice to use the same name for both the property and the private field, but with an uppercase first letter. The get method returns the value of the variable name . The set method assigns a value to the name variable. The value keyword represents the value we assign to the property.
Get = to obtain, to receive, to buy. The word 'get' can be used as a verb to express the actions of obtaining, receiving or buying. To form a sentence, we use get + direct object or get + indirect object + object.
you can remove get and set it will not affect the code and working due to the reason that you have defined a variable of type int with the Access type of public so that properties are mostly used to access the private members of class which is in your case do not exist so go on and remove it how ever if in top most ...
One word: inheritance.
Properties are inheritable while fields are not. You can use fields in an inherited class, but not alter their behavior by making them virtual.
Like so:
public class Foo { public virtual int MyField = 1; // Nope, this can't public virtual int Bar {get; set; } } public class MyDerive : Foo { public override MyField; // Nope, this can't public override int Bar { get { //do something; } set; } }
Edit: Besides the fact of inheritance, the points pointed out in the other answers (like visibility) are also a huge benefit of properties over fields.
One thing you can do with properties that you can't do with fields is limit visibility for either setter or getter:
public string MyProperty { get; private set; }
Something I use quite a lot.
And something (more powerful) you can't do with fields is define them inside an interface. Suppose you want an interface that requires implementing classes to have a certain property:
public interface MyInterface { string MyProperty { get; } }
Note that you do not need to have a setter here. It is entirely up to implementing classes to determine how they should set MyProperty
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With